SQL Server中的分组查询帮助
我试图按特定人群对我的数据进行排序。我的数据如下所示:SQL Server中的分组查询帮助,sql,sql-server,sql-server-2005,Sql,Sql Server,Sql Server 2005,我试图按特定人群对我的数据进行排序。我的数据如下所示: 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
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是ID5555,Direct是其他任何内容
我只是不知道如何使用“if”语句来实现,或者是否需要在“groupby”中实现
谢谢大家! 您可以使用case语句来实现这一点 像 用例小句
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
您的ID筛选器每次选择仅返回一个ID。对吗?
select case [ID]
when 5555 then 'Web'
else 'Direct'
end as [ID]
from mytable