我有这个简单的查询:
SELECT YEAR(P.DateCreated)
,MONTH(P.DateCreated)
,COUNT(*) AS cnt
FROM tbl1,
tbl2....
GROUP BY
MONTH(P.DateCreated)
,YEAR(P.DateCreated)
这会发出:
现在我需要相同的查询,但每年只使用groupby :
所以:
SELECT YEAR(P.DateCreated)
,COUNT(*) AS cnt
FROM tbl1,
tbl2....
GROUP BY
YEAR(P.DateCreated)
我不想要进行2次查询。
有什么方法可以在这里做group by
这个意思吗?
我可以将一个替换为另一个,但我不能执行一个被两个替换...
GROUP BY
CASE WHEN @timeMode='y' THEN YEAR(P.DateCreated)
WHEN @timeMode='m' THEN MONTH(P.DateCreated), YEAR(P.DateCreated) end
任何帮助?
答案 0 :(得分:17)
使用两个单独的查询会更好,但可以像
那样进行GROUP BY YEAR(P.DateCreated),
CASE
WHEN @timeMode='m' THEN MONTH(P.DateCreated) end
作为WHEN @timeMode <> 'm'
,所有行的第二个GROUP BY
表达式将为NULL
,不会影响结果。
答案 1 :(得分:6)
您可以使用over
子句在一个查询中返回每年和每月的计数:
SELECT distinct YEAR(P.DateCreated) as Year
, MONTH(P.DateCreated) as Month
, COUNT(*) over (partition by YEAR(P.DateCreated), MONTH(P.DateCreated))
as MonthCount
, COUNT(*) over (partition by YEAR(P.DateCreated)) as YearCount
FROM YourTable P