SQL选择DayOfWeek作为列标题

时间:2014-09-01 10:22:12

标签: sql sql-server-2008

我正在编写一份SQL报告,按星期几报告目标,例如我需要以类似的格式实现输出:TargetName,Target%,Mon,Tue,Weds,Thurs等星期几将显示该目标被击中的次数。

编写SQL以加入每个目标名称的相关表没有问题。我的问题是如何包含其他标题并按上述格式按标题显示相关数据?

感谢您的时间,

1 个答案:

答案 0 :(得分:1)

使用 DayOfWeek 了解日期所代表的工作日。然后用案例结构总结相应的日期:

select 
  targetname, 
  sum(case when datepart(weekday,logdate) = 2 then hits end) as monday, 
  sum(case when datepart(weekday,logdate) = 3 then hits end) as tuesday, 
  sum(case when datepart(weekday,logdate) = 4 then hits end) as wednesday, 
  sum(case when datepart(weekday,logdate) = 5 then hits end) as thursday, 
  sum(case when datepart(weekday,logdate) = 6 then hits end) as friday, 
  sum(case when datepart(weekday,logdate) = 7 then hits end) as saturday, 
  sum(case when datepart(weekday,logdate) = 1 then hits end) as sunday
from targets
group by targetname
order by targetname;

工作日的DatePart取决于DATEFIRST的设置。以上陈述假设第一天是星期日。