我正在尝试按某些人群对数据进行排序。我的数据看起来像:
Origional_Date ID FORM Total
2012-03-01 1855 3 1283
2012-03-01 2869 4 2306
2012-03-01 5555 4 6440
2012-03-01 5555 3 8373
2012-03-01 2527 3 8476
2012-03-01 922 3 823
2012-03-15 2907 4 1420
2012-03-15 5555 3 2892
2012-03-15 2914 4 5008
2012-03-15 2375 3 4594
我到目前为止的查询是:
DECLARE @StartDate smalldatetime, @EndDate smalldatetime, @Web_ID as smallint
SET @StartDate = '20120301'
SET @EndDate = '20120331'
SET @Web_ID = '5555'
SELECT DATEADD(WEEK, DATEDIFF(WEEK, 0, [Origional_Date]), -1) as [Origional_Date]
,[ID]
,[Form]
,SUM([Total]) as [Total]
FROM mytable
WHERE [Origional_Date] between @StartDate and @EndDate
AND [ID] = @Web_ID
GROUP BY DATEADD(WEEK, DATEDIFF(WEEK, 0, [Origional_Date]), -1), [ID], [Form]
ORDER BY [Origional_Date], [Form] ASC
我要做的是显示我的数据:
Origional_Date ID FORM Total
2012-03-01 Web 3 8373
2012-03-01 Direct 3 10582
2012-03-01 Web 4 6440
2012-03-01 Direct 4 2306
2012-03-15 WEB 3 2892
2012-03-15 Direct 3 4594
2012-03-15 Direct 4 6428
其中Web为ID 5555,Direct为其他任何内容。
我只是不确定如果可以使用“IF”语句完成此操作,或者是否需要在“group by”中完成
谢谢!
答案 0 :(得分:1)
您可以使用案例陈述来实现这一目标。
像
SELECT DATEADD(WEEK, DATEDIFF(WEEK, 0, [Origional_Date]), -1) as [Origional_Date]
,(CASE WHEN [ID] = 5555 THEN 'Web' ELSE 'Direct' END )
,[Form]
,SUM([Total]) as [Total]
FROM mytable
WHERE [Origional_Date] between @StartDate and @EndDate
AND [ID] = @Web_ID
GROUP BY DATEADD(WEEK, DATEDIFF(WEEK, 0, [Origional_Date]), -1), (CASE WHEN [ID] = 5555 THEN 'Web' ELSE 'Direct' END ), [Form]
ORDER BY [Origional_Date], [Form] ASC
答案 1 :(得分:1)
使用Case clausule
select case active
when 1 then 'Active'
when 0 then 'Inactive'
end
from contract
在你的情况下,与此类似:
select case [ID]
when 5555 then 'Web'
else 'Direct'
end as [ID]
from mytable