所以我有这样的数据
id type date
1 1 2015-02-04
2 1 2015-02-04
3 2 2015-02-04
4 1 2015-02-05
5 2 2015-02-06
我想要一个像这样的结果
countForType1 countForType2 dow
2 1 Wednesday
1 0 Thursday
0 1 Friday
etc...
我尝试使用OVER(PARTITION
,但我认为我使用不正确,或者可能,我需要使用其他内容。这是我目前的查询:
SELECT
COUNT(seatType) OVER(PARTITION BY seatType) AS Counts,
CASE DATEPART(DW,testDate)
WHEN 1 THEN 'Sunday'
WHEN 2 THEN 'Monday'
WHEN 3 THEN 'Tuesday'
WHEN 4 THEN 'Wednesday'
WHEN 5 THEN 'Thursday'
WHEN 6 THEN 'Friday'
WHEN 7 THEN 'Saturday'
END dow
FROM tst_Tests
WHERE roomid = 1
GROUP BY DATEPART(DW,testDate), seatType
我不确定如何根据各个座位类型创建第二列。 我想我可以在select语句中放入两个select语句,但这似乎效率低下。我觉得有一个功能,我使用不正确或根本没有。
编辑:我让示例数据与实际日期和返回的数字相匹配。
答案 0 :(得分:0)
您应该使用Conditional Aggergate
代替window function
SELECT Count(CASE WHEN type = 1 THEN 1 END) AS countForType1,
Count(CASE WHEN type = 2 THEN 1 END) AS countForType2,
CASE
WHEN Datepart(DW, date) = 1 THEN 'Sunday'
WHEN Datepart(DW, date) = 2 THEN 'Monday'
WHEN Datepart(DW, date) = 3 THEN 'Tuesday'
WHEN Datepart(DW, date) = 4 THEN 'Wednesday'
WHEN Datepart(DW, date) = 5 THEN 'Thursday'
WHEN Datepart(DW, date) = 6 THEN 'Friday'
WHEN Datepart(DW, date) = 7 THEN 'Saturday'
END dow
FROM Yoursampletable
GROUP BY Datepart(DW, date)
答案 1 :(得分:0)
喜欢这个吗?
DECLARE @Example TABLE ([Id] int, [type] int, [testDate] date)
INSERT INTO @Example ([Id], [type], [testDate])
SELECT 1,1,'2015-02-04' UNION ALL
SELECT 2,1,'2015-02-04' UNION ALL
SELECT 3,2,'2015-02-04' UNION ALL
SELECT 4,1,'2015-02-05' UNION ALL
SELECT 5,2,'2015-02-06'
;with rowsWithDayName as (
select *,
CASE WHEN DATEPART(DW,testDate) = 1 THEN 'Sunday'
WHEN DATEPART(DW,testDate) = 2 THEN 'Monday'
WHEN DATEPART(DW,testDate) = 3 THEN 'Tuesday'
WHEN DATEPART(DW,testDate) = 4 THEN 'Wednesday'
WHEN DATEPART(DW,testDate) = 5 THEN 'Thursday'
WHEN DATEPART(DW,testDate) = 6 THEN 'Friday'
WHEN DATEPART(DW,testDate) = 7 THEN 'Saturday'
END as [DayName]
from @Example
)
select
SUM(CASE WHEN [type]=1 THEN 1 ELSE 0 END) as countForType1
, SUM(CASE WHEN [type]=2 THEN 1 ELSE 0 END) as countForType2
, [DayName]
FROM rowsWithDayName
group by [DayName]