如何在GROUP BY子句中使用聚合函数?
SELECT VCH_DCOA_CODE, SUM(VCH_DEFINATION.VCH_CREDIT) AS Debit
FROM VCH_DEFINATION
GROUP BY SUBSTRING(VCH_DCOA_CODE, 0, 6)
答案 0 :(得分:2)
看起来您希望显示sum()
的完整VCH_DCOA_CODE
但group by
子字符串值,所以我猜你想要这个:
SELECT v1.VCH_DCOA_CODE, v2.Debit
FROM VCH_DEFINATION v1
INNER JOIN
(
select SUM(VCH_DEFINATION.VCH_CREDIT) AS Debit, SUBSTRING(VCH_DCOA_CODE, 0, 6) Shortcode
from VCH_DEFINATION
group by SUBSTRING(VCH_DCOA_CODE, 0, 6)
) v2
on v1.SUBSTRING(VCH_DCOA_CODE, 0, 6) = v2.Shortcode
子查询将为每个SUM()
获取SUBSTRING(VCH_DCOA_CODE, 0, 6)
,但随后会显示每个VCH_DCOA_CODE
但是,如果您不想显示完整的VCH_DCOA_CODE
,那么您可以使用内部查询来获得结果:
select SUM(VCH_DEFINATION.VCH_CREDIT) AS Debit, SUBSTRING(VCH_DCOA_CODE, 0, 6) Shortcode
from VCH_DEFINATION
group by SUBSTRING(VCH_DCOA_CODE, 0, 6)
答案 1 :(得分:1)
您必须将SUBSTRING(VCH_DCOA_CODE, 0, 6)
添加到select
子句中,如下所示:
SELECT SUBSTRING(VCH_DCOA_CODE, 0, 6), SUM(VCH_DEFINATION.VCH_CREDIT) AS Debit
FROM VCH_DEFINATION
GROUP BY SUBSTRING(VCH_DCOA_CODE, 0, 6)