按组选择SQL

时间:2017-07-04 01:51:39

标签: sql-server

我尝试按组计算,但我收到此错误:

  

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

有人可以帮助我吗?

SELECT
    NT4                AS nt,
    LN0617.OFFCR       AS OfficeCode,
    ln0617.RATE * 100  AS LaiSuat,
    SUM( ln0617.CBAL ) AS SoDu,
    ln0617.RATE * 100 * sum( ln0617.CBAL ) AS LS1
FROM
    [dbo].[SIL_CM] 
    JOIN [dbo].[LN0617] ON
    (
        ln0617.ACCTNO = SIL_CM.TK
        AND
        ln0617.CBAL <> 0
        AND
        SIL_CM.TKTYPE='L'
    )
GROUP BY
    sil_cm.NT4,
    LN0617.OFFCR,
    ln0617.RATE * 100
ORDER BY
    LN0617.OFFCR,
    ln0617.RATE * 100

2 个答案:

答案 0 :(得分:0)

我在选择列表中看到的唯一可能问题是以下行:

ln0617.RATE*100*sum(ln0617.CBAL) as LS1

SQL Server可能会抱怨ln0617.RATE,因为它与聚合函数混合在一起。这里的一个选择是将ln0617.RATE移到总和中:

select
    NT4 as nt,
    LN0617.OFFCR as OfficeCode,
    ln0617.RATE*100 as LaiSuat,
    sum(ln0617.CBAL) as SoDu,
    100*sum(ln0617.RATE * ln0617.CBAL) as LS1
from [dbo].[SIL_CM]
...

这应该有效,因为乘法是可交换的。

答案 1 :(得分:0)

我相信你只需要引用列进行分组,因为* 100是常量

SELECT
      NT4                                               AS nt
    , LN0617.OFFCR                                      AS OfficeCode
    , ln0617.RATE * 100                                 AS LaiSuat
    , SUM(ln0617.CBAL)                                  AS SoDu
    , SUM(ln0617.CBAL * ln0617.RATE) / SUM(ln0617.cbal) AS LS1
FROM [dbo].[SIL_CM] SIL_CM
JOIN [dbo].[LN0617] LN0617 ON ln0617.ACCTNO = SIL_CM.TK
WHERE ln0617.CBAL <> 0
      AND SIL_CM.TKTYPE = 'L'
GROUP BY
      sil_cm.NT4
    , LN0617.OFFCR
    , ln0617.RATE
ORDER BY
      LN0617.OFFCR
    , ln0617.RAT