我的表格结构如下。
表名:时刻表
timetable http://www.4shared.com/download/MYafV7-6ce/timetableTable.png
表名:slot_Table
timetable http://www.4shared.com/download/9Lp_CBn2ba/slot_table.png
表名:讲师(此表不是此特定问题所必需的)
我想在我的android应用程序中以类似这样的时间表格式显示结果数据:
random http://www.4shared.com/download/oAGiUXVAba/random.png
问题:我应该写什么样的查询,以便特定日期的主题和相应的时段将是查询的结果?
1)日期应按顺序排列,如星期一、星期二、星期三。
2)如果星期一在两个不同的时段中有两个受试者,则显示如下:

Day         7:30-9:10AM           9:20-11:00AM

Monday      Android Workshop      Operating System

这只是个样本。
备注:由于课程表的格式是必需的,所以所有日期(星期一到星期六)的课程号都必须在里面。
编辑:
我试过这个
select day,subject,slot from timetable,slot_table where timetable.slotid = slot_table.slotid

结果是:
a 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

导致
a http://www.4shared.com/download/rZW20_g8ce/random2.png
所以现在它显示周一在两个时段有两个类,周二在一个时段有一个类,以此类推。
现在有什么可以在周一显示两个时段(计时)的查询帮助吗?
解决方案:
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

结果:
a http://www.4shared.com/download/1w7Tyicfce/random3.png

最佳答案

您需要的是一个透视查询。在其中一个选项中,您有一个select,它以行的形式提供数据,就像您的结果就在EDIT(Day,subject,slot)下面一样。然后需要指定要“透视”为列的行的值(本例中为槽)。因为透视依赖于要透视的列的值,所以很难编写一般查询,Postgres Wiki有一个使用dymanic SQL的示例以及在http://wiki.postgresql.org/wiki/Pivot_query
在您的情况下,考虑到插槽看起来是固定的,您可能能够硬编码它们(这是您自己的决定)。
NB我不是Postgres用户,但看起来它可以做到(如果不能做到,我会非常惊讶)。

关于sql - SQL查询从时间戳列表中生成时间x天网格?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21313611/

10-14 20:51
查看更多