我有以下查询,它是对季度的简单计数,但是我希望根据迄今为止的Year(不是以前的记录)产生累积计数。唯一的方法就是通过指针吗?
MS SQL Server,TPO_CQuarter的数据类型为varchar。
所需结果:
TPO_CQuarter Days
2016-1 112
2016-2 196
2016-3 280
2016-4 364
2017-1 111
2017-2 195
2017-3 279
2017-4 363
2018-1 112
2018-2 196
2018-3 280
2018-4 298
查询:
SELECT T.TPO_CQuarter
,COUNT(DISTINCT TPO_CFecha)
FROM TH_Rotacion R
INNER JOIN TD_Tiempo T ON R.TPO_KFECHA=T.TPO_KFecha
GROUP BY T.TPO_CQuarter
ORDER BY T.TPO_CQuarter ASC
答案 0 :(得分:1)
尝试一下:
SELECT TPO_CQuarter, SUM(Days) OVER (ORDER BY TPO_CQuarter) CumSum FROM (
SELECT T.TPO_CQuarter
,COUNT(DISTINCT TPO_CFecha) Days
FROM TH_Rotacion R
INNER JOIN TD_Tiempo T ON R.TPO_KFECHA=T.TPO_KFecha
GROUP BY T.TPO_CQuarter
ORDER BY T.TPO_CQuarter ASC
) a
带有SUM
子句的窗口函数ORDER BY
用作累积总和。
答案 1 :(得分:1)
您需要一个累计总和/运行总计:
SELECT T.TPO_CQuarter
-- cumulative sum
,SUM(COUNT(DISTINCT TPO_CFecha))
OVER (PARTITION BY SUBSTRING(TPO_CFecha FROM 1 FOR 4) -- reset for each year
ORDER BY TPO_CQuarter
ROWS UNBOUNDED PRECEDING)
FROM TH_Rotacion R
INNER JOIN TD_Tiempo T ON R.TPO_KFECHA=T.TPO_KFecha
GROUP BY T.TPO_CQuarter
ORDER BY T.TPO_CQuarter ASC
答案 2 :(得分:1)
如果您有年份列,则可以表示为:
SELECT T.TPO_CQuarter,
COUNT(DISTINCT TPO_CFecha) as days_in_quarter,
SUM(COUNT(DISTINcT TPPO_CFecha) OVER (PARTITION BY T.TPC_CYear ORDER BY T.TPO_CQuarter) as days
FROM TH_Rotacion R INNER JOIN
TD_Tiempo T
ON R.TPO_KFECHA = T.TPO_KFecha
GROUP BY T.TPO_CQuarter, T.TPO_CYear
ORDER BY T.TPO_CQuarter ASC;
否则,您可以使用LEFT()
:
SELECT T.TPO_CQuarter,
COUNT(DISTINCT TPO_CFecha) as days_in_quarter,
SUM(COUNT(DISTINCT TPPO_CFecha) OVER (PARTITION BY LEFT(T.TPO_CQuarter, 4) ORDER BY T.TPO_CQuarter) as days
FROM TH_Rotacion R INNER JOIN
TD_Tiempo T
ON R.TPO_KFECHA = T.TPO_KFecha
GROUP BY T.TPO_CQuarter
ORDER BY T.TPO_CQuarter ASC;