我有一个查询,可以使用GROUP BY
获取特定日期的数量总和,但该查询会给我NULL
个结果而不会聚合某些值。
以下是查询:
Select
VPC.Armazem as TARMA
,YEAR(VPC.data) as DataTotal
,CASE WHEN VP.combustivel = 1 THEN ISNULL(SUM(VPL.QTD), 0) END as ADITIVADA
,CASE WHEN VP.combustivel = 2 THEN ISNULL(SUM(VPL.QTD), 0) END as X98
,CASE WHEN VP.combustivel = 3 THEN ISNULL(SUM(VPL.QTD), 0) END as X95
,CASE WHEN VP.combustivel = 4 THEN ISNULL(SUM(VPL.QTD), 0) END as XGAS
,CASE WHEN VP.combustivel = 5 THEN ISNULL(SUM(VPL.QTD), 0) END as XGPL
,CASE WHEN VP.combustivel = 6 THEN ISNULL(SUM(VPL.QTD), 0) END as XAGR
,CASE WHEN VP.combustivel = 7 THEN ISNULL(SUM(VPL.QTD), 0) END as MISTURA
,CASE WHEN VP.combustivel = 9 THEN ISNULL(SUM(VPL.QTD), 0) END as XAQ
,CASE WHEN VP.combustivel = 10 THEN ISNULL(SUM(VPL.QTD), 0) END as ADIESEL
,CASE WHEN VP.combustivel = 11 THEN ISNULL(SUM(VPL.QTD), 0) END as ADBLUE
,CASE WHEN VP.combustivel = 12 THEN ISNULL(SUM(VPL.QTD), 0) END as O95
,CASE WHEN VP.combustivel = 13 THEN ISNULL(SUM(VPL.QTD), 0) END as O98
FROM
CB_VendasPOS (nolock) as VP
INNER JOIN vendaspos_linhas (nolock) as VPL on VPL.autoreg=VP.autoreg
INNER JOIN VendasPOS_Cabecalhos (nolock) as VPC on VPC.Prenumero=VPL.Prenumero
INNER JOIN VendasPOS_Turnos (nolock) as VPT on VPT.CodTurnoAuto=VPC.CodTurnoAuto
WHERE
(MONTH(VPC.data) >= MONTH('2015-09-01') AND MONTH(VPC.data) <= MONTH('2015-09-01'))
and (YEAR(VPC.data) >= YEAR('2014-09-01') AND YEAR(VPC.data) <= YEAR('2015-09-01'))
and (VPT.armazem='454' or Len('454')=0)
and FACT_VD NOT IN ('A', 'I', 'G', 'M')
GROUP BY
YEAR(VPC.data)
,VPC.Armazem
,VP.combustivel
ORDER BY
VPC.Armazem
,YEAR(VPC.data)
如何将结果汇总到每年只显示一次?
我正在使用MS SQL
答案 0 :(得分:0)
我怀疑你想要条件聚合:
Select VPC.Armazem as TARMA, YEAR(VPC.data) as DataTotal,
SUM(CASE WHEN VP.combustivel = 1 THEN VPL.QTD ELSE 0 END) as ADITIVADA,
SUM(CASE WHEN VP.combustivel = 2 THEN VPL.QTD ELSE 0 END) as X98,
. . .
FROM . . .
GROUP BY YEAR(VPC.data), VPC.Armazem
. . .
请注意,VP.combustivel
不在GROUP BY
。