我有针对ID的出勤记录,显示他/她当天是否在场,我想通过sql查询在一行中显示数据,该行是针对该ID的多行。所以请尽快帮我解决这个问题。
执行查询后从数据库中获取此结果:
abc 1/2/2013 Present
abc 2/2/2013 Present
abc 3/2/2013 Present
abc 4/2/2013 Present
abc 5/2/2013 Present
abc 6/2/2013 Present
Expected Result:
Name Date1 Date2 Date3 Date4 Date5
abc Present Present Present Present Present
答案 0 :(得分:1)
如果您不能使用PIVOT
,则可以使用行号和分组(DEMO)获得相同的效果:
select
name
,max(case when rn=1 then description end) as date1
,max(case when rn=2 then description end) as date2
,max(case when rn=3 then description end) as date3
,max(case when rn=4 then description end) as date4
,max(case when rn=5 then description end) as date5
from (
select name, date, description,
row_number() over (partition by name order by date) rn from Table1
) T
group by name
请注意,这只会处理您在查询中硬编码的日期。如果它必须是动态的(即,您不知道提前需要多少个日期列),那么您可能需要根据每个组的最大日期计数动态生成上面的SQL代码。