我想从GROUP BY
条款中排除一个术语,阻止我将术语汇总在一起。奇怪的是,我在case语句中使用了导致this的术语,并且查询仍然希望我在group by子句中使用它,否则它将生成错误。如何解决这个问题?
更具体一点:SELECT
子句中案例中使用的vr.krebel也迫使我添加它GROUP BY
。怎么避免这个?
SELECT vr.ktonr,
vr.foretagkod,
'' AS persign,
'' AS TYPE,
NULL,
1 AS antal,
SUM(vr.debbel-vr.krebel),
0,
vr.kostbar,
vr.koststallekod,
vr.projcode,
vr.redovisnar,
vr.period,
'Allocated vouchers' AS artbeskr,
ko.ktobeskr AS kodescr,
CASE
WHEN ((vr.ktonr LIKE '9600'
OR vr.ktonr LIKE '3%')
AND (vr.krebel>0)) THEN 'Revenues'
ELSE 'Costs'
END
FROM vr
INNER JOIN ko ON ko.ktonr=vr.ktonr
AND ko.redovisnar=datepart(YEAR,vr.bokfdat)
AND ko.foretagkod=vr.foretagkod
WHERE vr.foretagkod = 300
AND vr.intsource = 20
AND vr.projcode = 50040
AND (vr.bokfdat BETWEEN CAST('2012-12-01' AS DATETIME) AND CAST('2012-12-31' AS DATETIME))
GROUP BY vr.ktonr,
vr.foretagkod,
vr.kostbar,
vr.koststallekod,
vr.projcode,
vr.redovisnar,
vr.period,
ko.ktobeskr,
vr.krebel
更具体一点:SELECT
子句中案例中使用的vr.krebel也迫使我添加GROUP BY
,如何避免这种情况?
答案 0 :(得分:4)
这里有不同的选择。但我认为,对于您的查询而言,更好的方法是在CASE
中添加GROUP BY
。
select vr.ktonr,
vr.foretagkod,
'' as persign,
'' as Type,
NULL,
1 as antal,
SUM(vr.debbel-vr.krebel),
0,
vr.kostbar,
vr.koststallekod,
vr.projcode,
vr.redovisnar,
vr.period,
'Allocated vouchers' as artbeskr,
ko.ktobeskr as kodescr,
case when ((vr.ktonr like '9600' or vr.ktonr like '3%')
AND (vr.krebel>0)) then 'Revenues' else 'Costs' end
from vr
inner join ko
on ko.ktonr=vr.ktonr
AND ko.redovisnar=datepart(year,vr.bokfdat)
AND ko.foretagkod=vr.foretagkod
where vr.foretagkod = 300
AND vr.intsource = 20
AND vr.projcode = 50040
AND (vr.bokfdat between CAST('2012-12-01' AS DATETIME)
AND CAST('2012-12-31' AS DATETIME))
group by vr.ktonr,
vr.foretagkod,
vr.kostbar,
vr.koststallekod,
vr.projcode,
vr.redovisnar,
vr.period,
ko.ktobeskr,
case when ((vr.ktonr like '9600' or vr.ktonr like '3%')
AND (vr.krebel>0)) then 'Revenues' else 'Costs' end