我有以下内容:
http://sqlfiddle.com/#!6/226ae/1
我现在尝试为一年中的每周添加一行,并相应地过滤联系人。 CONTACTS有一个datetime列。新表格如下:
Status 1 Status 2 Status 3
Week 1 3 4 2
Week 2 1 5 3
Week 3 2 2 4
我认为需要使用DATEADD,但是我在如何开始更改查询方面感到茫然。
我知道MySQL有一个GROUP BY WEEK命令,但我不认为SQL有一个等价的。实现这一目标的最佳方法是什么?
答案 0 :(得分:29)
如果数据跨越多年,您可以使用DATEPART()
,按周和年份分组:
SELECT
'Week ' + cast(datepart(wk, created) as varchar(2)) Week,
SUM(case WHEN status = 1 then 1 else 0 end) Status1,
SUM(case WHEN status = 2 then 1 else 0 end) Status2,
SUM(case WHEN status = 3 then 1 else 0 end) Status3,
SUM(case WHEN status = 4 then 1 else 0 end) Status4,
SUM(case WHEN status = 5 then 1 else 0 end) Status5
FROM contacts
group by datepart(wk, created), year(created)
将年份添加到最终结果中:
SELECT
'Week ' + cast(datepart(wk, created) as varchar(2)) Week,
year(created) year,
SUM(case WHEN status = 1 then 1 else 0 end) Status1,
SUM(case WHEN status = 2 then 1 else 0 end) Status2,
SUM(case WHEN status = 3 then 1 else 0 end) Status3,
SUM(case WHEN status = 4 then 1 else 0 end) Status4,
SUM(case WHEN status = 5 then 1 else 0 end) Status5
FROM contacts
group by datepart(wk, created), year(created)
答案 1 :(得分:1)
您可以使用the datepart
function从日期中提取一周。
查询变为:
SELECT datepart(week, created) as week,
SUM(case WHEN status = 1 then 1 else 0 end) Status1,
SUM(case WHEN status = 2 then 1 else 0 end) Status2,
SUM(case WHEN status = 3 then 1 else 0 end) Status3,
SUM(case WHEN status = 4 then 1 else 0 end) Status4,
SUM(case WHEN status = 5 then 1 else 0 end) Status5
FROM contacts
group by datepart(week, created)
SqlFiddle:http://sqlfiddle.com/#!6/226ae/6tsq
答案 2 :(得分:0)
您可以尝试在查询中使用group by子句:
SELECT
DATE_FORMAT( created, '%u' ) week_number,
SUM(case WHEN status = 1 then 1 else 0 end) Status1,
SUM(case WHEN status = 2 then 1 else 0 end) Status2,
SUM(case WHEN status = 3 then 1 else 0 end) Status3,
SUM(case WHEN status = 4 then 1 else 0 end) Status4,
SUM(case WHEN status = 5 then 1 else 0 end) Status5
FROM contacts
GROUP BY DATE_FORMAT( created, '%u' )
我假设你在谈论mysql。
此处记录了DATE_FORMAT函数:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format