2016-12-19 44 views
1

我正在构建一个计划应用程序,该应用程序使用我校的预定义API。每个课程都有一次为每小时申报一次。一个简单的例子:SQLite - GROUP BY行,仅当某些列匹配另一列时

表教训:

Subject   Id  Start  End 

English   111  09:30  10:30 
English   111  10:30  11:30 
Dutch   120  12:30  13:30 
Java   109  14:30  15:30 
English   111  15:30  16:30 

要检索的教训,向他们展示我的应用程序里面,我用下面的查询:

SELECT MIN(start), MAX(end) FROM lessons ORDER BY Start GROUP BY Id 

它工作得很好但是,当一名学生每天在同一个ID上有两个相同的课程时,在这种情况下,English,SQL查询将显示为:

English 09:30 - 16:30 

在这种情况下,我们有一个问题,因为英语并不需要6个小时,我想它显示为:

English 09:30 - 11:30 
English 15:30 - 16:30 

所以我的问题是:我应该用只有GROUP BY教训时 什么查询startend值等于具有相同ID的另一行,以避免错误时间?,我可以通过编程实现,但我更喜欢使用SQL来完成此操作。

编辑:

我通过分组,因为我不希望显示每节课作为一个单独的行,因为我的学校每lessonhour定义为单行。

+0

? –

+0

@a_horse_with_no_name我的学校将所有内容都返回为JSON转储。我解析一切到Android SQLite数据库。 –

+0

我没有任何意义。为什么你在第一个地方分组? –

回答

1

这将做您正在使用哪个数据库管理系统的工作

with  cte as 
      (
       select  subject,id,start,end 
       from  mytable t 
       where  not exists 
          (
           select  null 
           from  mytable t2 
           where  t2.id = t.id 
             and t2.end = t.start 
          )  

       union all 

       select  t.subject,t.id,cte.start,t.end 

       from     cte  
          join  mytable t 
          on   t.id = cte.id 
            and t.start = cte.end 
      ) 

select  subject,id,start,max(end) as end 

from  cte 

group by subject,id,start   

+---------+-----+-------+-------+ 
| subject | id | start | end | 
+---------+-----+-------+-------+ 
| Dutch | 120 | 12:30 | 13:30 | 
+---------+-----+-------+-------+ 
| English | 111 | 09:30 | 11:30 | 
+---------+-----+-------+-------+ 
| English | 111 | 15:30 | 16:30 | 
+---------+-----+-------+-------+ 
| Java | 109 | 14:30 | 15:30 | 
+---------+-----+-------+-------+ 
+0

它可能不是很清楚,但我正在使用SQLite,我会试试这个。 –

+0

这是测试SQLite 3.8.11 –

+0

谢谢,我不得不调整查询了一下,但有一个小错误:android.database.sqlite.SQLiteException:选择到UNION ALL的左侧和右侧没有相同的结果列数(代码1); –