组和聚合函数问题

时间:2017-01-19 21:12:22

标签: sql

SELECT HCIS,ServiceDate,PrimeInsMnemonic,TIN,Amount,SUM(Amount) AS Total
FROM dbo.PbrChargeTransactions
WHERE HCIS = 'ASL'
AND ServiceDate Between'01/01/16' and '12/31/16'
AND PrimeInsMnemonic = 'MED'
AND TIN in ('460224598','46-0224598')
GROUP By HCIS
ORDER BY SUM(Amount) 

我得到的错误:

Msg 8120,Level 16,State 1,Line 1 专栏' dbo.PbrChargeTransactions.ServiceDate'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

我希望有人能够向我解释为什么这不起作用?

提前感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

我认为这个消息很清楚。所有未聚合的列都应位于GROUP BY中。因此,请删除不使用的列:

SELECT HCIS, SUM(Amount) AS Total
FROM dbo.PbrChargeTransactions
WHERE HCIS = 'ASL' AND
      ServiceDate Between '2016-01-01' AND '2016-12-31' AND
      PrimeInsMnemonic = 'MED' AND
      TIN in ('460224598','46-0224598')
GROUP By HCIS
ORDER BY SUM(Amount) 

答案 1 :(得分:0)

如果它们不在聚合函数

中,您应该在Select语句中包含每个列以在Group By中重复

SELECT HCIS,ServiceDate,PrimeInsMnemonic,TIN,Amount,SUM(Amount)AS Total 来自dbo.PbrChargeTransactions HCIS =' ASL' AND ServiceDate在&01; 01/01/16'和' 12/31/16' AND PrimeInsMnemonic =' MED' AND TIN in(' 460224598',' 46-0224598') GROUP By HCIS,ServiceDate,PrimeInsMnemonic,TIN,Amount 按顺序订购(金额)

答案 2 :(得分:0)

正如他们所说,你必须按照选择中的列输入组。

SELECT HCIS,ServiceDate,PrimeInsMnemonic,TIN,Amount,SUM(Amount) AS Total
FROM dbo.PbrChargeTransactions
WHERE HCIS = 'ASL'
AND ServiceDate Between'01/01/16' and '12/31/16'
AND PrimeInsMnemonic = 'MED'
AND TIN in ('460224598','46-0224598')
GROUP By HCIS,ServiceDate,PrimeInsMnemonic,TIN,Amount
ORDER BY SUM(Amount)