可以在同一个Group By
中添加多个Select
子句吗?我正在做一个商店程序,想要返回一系列天数的值。如果这个天数超过一个数量,那么我想group by
这几个月,如果这个月回归的年份大于一年,我想要返回年份的名称。
数据只是表的当前ID,具有多个日期值的另一个表的ID,所有日期都与其他表ID唯一。
我只想返回外部表摘要的所有日期。
SELECT
SUM(D.VALUE) SUM_VALUE,
CASE
WHEN DATEDIFF(month,MIN(D.DATE_FIELD),MAX(D.DATE_FIELD)) > 12 THEN YEAR(D.DATE_FIELD)
WHEN DATEDIFF(week,MIN(D.DATE_FIELD),MAX(D.DATE_FIELD)) > 12 THEN DATEPART(WK, D.DATE_FIELD) + ' ' + YEAR(D.DATE_FIELD)
ELSE DATEPART(DAY, D.DATE_FIELD) + ' ' + DATEPART(WK, D.DATE_FIELD) + ' ' + YEAR(D.DATE_FIELD)
END AS NAME
FROM VALUE_DATE_TABLE D
WHERE D.ANOTHER_TABLE_ID = @some_ID
GROUP BY (
YEAR(D.DATE_FIELD)
HAVING
DATEDIFF(month,MIN(D.DATE_FIELD),MAX(D.DATE_FIELD)) > 12
OR
DATEPART(WK, D.DATE_FIELD), YEAR(D.DATE_FIELD)
HAVING
DATEDIFF(week,MIN(D.DATE_FIELD),MAX(D.DATE_FIELD)) > 12
OR
DATEPART(DAY, D.DATE_FIELD), DATEPART(WK, D.DATE_FIELD), YEAR(D.DATE_FIELD))
我试图做多个groups by
。
这个想法是在选择
中完成这3个组Group by YEAR(D.DATE_FIELD)
Group by DATEPART(WK, D.DATE_FIELD), YEAR(D.DATE_FIELD)
Group by DATEPART(DAY, D.DATE_FIELD), DATEPART(WK, D.DATE_FIELD), YEAR(D.DATE_FIELD)
答案 0 :(得分:1)
您可以使用GROUP BY GROUPING SETS()
:
SELECT
SUM(D.VALUE) SUM_VALUE,
CASE
WHEN DATEDIFF(month,MIN(D.DATE_FIELD),MAX(D.DATE_FIELD)) > 12
THEN YEAR(D.DATE_FIELD)
WHEN DATEDIFF(week,MIN(D.DATE_FIELD),MAX(D.DATE_FIELD)) > 12
THEN DATEPART(WK, D.DATE_FIELD) + ' ' + YEAR(D.DATE_FIELD)
ELSE DATEPART(DAY, D.DATE_FIELD) + ' ' + DATEPART(WK, D.DATE_FIELD)
+ ' ' + YEAR(D.DATE_FIELD)
END AS NAME
FROM VALUE_DATE_TABLE D
WHERE D.ANOTHER_TABLE_ID = @some_ID
GROUP BY GROUPING SETS (
(YEAR(D.DATE_FIELD))
,(DATEPART(WK, D.DATE_FIELD), YEAR(D.DATE_FIELD))
,(DATEPART(DAY, D.DATE_FIELD), DATEPART(WK, D.DATE_FIELD), YEAR(D.DATE_FIELD))
);
修改强>
这是正确的方式,但我怎么告诉sql我正在使用哪个分组集
您可以使用GROUPING_ID
:
是一个计算分组级别的函数。只有在指定GROUP BY时,GROUPING_ID才能用于SELECT列表,HAVING或ORDER BY子句。