我的表的结构如下。
表名:时刻表
时间表http://www.4shared.com/download/MYafV7-6ce/timetableTable.png
表名:slot_table
时间表http://www.4shared.com/download/9Lp_CBn2ba/slot_table.png
表名:讲师(此表对于此特定问题不是必需的)
我想以时间表格式在我的android应用中显示结果数据,如下所示:
随机http://www.4shared.com/download/oAGiUXVAba/random.png
问题:我应该写什么查询,以便特定日期的主题与各自的时段成为查询的结果?
1)日期应按星期一,星期二,星期三的顺序排列。
2)如果星期一在2个不同的时段中有2个主题,则它应显示为:
Day 7:30-9:10AM 9:20-11:00AM
Monday Android Workshop Operating System
这只是一个示例。
附言:由于需要时间表格式,因此必须具有所有天(周一至周六)的时段ID的所有主题。
编辑:
我试过了
select day,subject,slot from timetable,slot_table where timetable.slotid = slot_table.slotid
结果:
一个http://www.4shared.com/download/uMU7NA8Oce/random1.png
但是我想要一个时间表格式,但我不知道该怎么做。
编辑:
时间表样本格式如下:
编辑:
我写了一个查询
select timetable.day,count(slot_table.subject) as no_of_classes from timetable,slot_table where timetable.slotid = slot_table.slotid group by timetable.day
导致
一个http://www.4shared.com/download/rZW20_g8ce/random2.png
因此,现在显示星期一有2个班级2个班级,星期二有1个班级1个班级,依此类推。
现在可以在星期一显示两个广告位(时间)的查询有任何帮助吗?
解决方案:
select timetable.day,max(case when (slot='7:30-9:10AM') then slot_table.subject END) as "7:30-9:10AM",max(case when (slot='9:20-11:00AM') then slot_table.subject END) as "9:20-11:00AM",max(case when (slot='11:10-12:50PM') then slot_table.subject END) as "11:10-12:50PM",max(case when (slot='1:40-3:20PM') then slot_table.subject END) as "1:40-3:20PM", max(case when (slot='3:30-5:00PM') then slot_table.subject END) as "3:30-5:00PM" from timetable join slot_table on timetable.slotid = slot_table.slotid group by timetable.day
结果:
您想要的称为PIVOT查询。在其中之一中,您可以选择以行形式提供数据,就像您在EDIT(日期,主题,广告位)下方的结果一样。然后,您需要指定要“透视”成为列的行的值(在此示例中为插槽)。由于数据透视表依赖于要旋转的列的值,因此很难编写一般查询,而Postgres Wiki上有一个使用动态SQL的示例以及许多可在http://wiki.postgresql.org/上生成它的代码。 Wiki /数据查询
在您的情况下,考虑到插槽看起来像是固定的,您可能可以对其进行硬编码(这是您自己做的决定)。
注意:我不是Postgres用户,但看起来可以做到(如果我做不到,我会感到非常惊讶)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句