【问题标题】:SQL Group By function combined with SUMSQL Group By 函数结合 SUM
【发布时间】:2019-01-08 09:01:55
【问题描述】:

我收到了错误

选择列表中的“Nordlux UK$Item.Description”列无效 因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句。

尝试运行 SQL 语句时。

如果我删除 SUM 函数并且 Group by 它可以工作,但我希望所有结果都按我的项目编号分组。 谁能看到我在代码中做错了什么?

SELECT
    [Nordlux UK$Item].No_,
    [Nordlux UK$Item].[Description],
    SUM([Nordlux UK$Item Ledger Entry].[Quantity]) AS Int
FROM [Nordlux UK$Item]
JOIN [Nordlux UK$Sales Price]
    ON [Nordlux UK$Item].[No_] = [Nordlux UK$Sales Price].[Item No_]
JOIN [Nordlux UK$Item Ledger Entry]
    ON [Nordlux UK$Item].[No_] = [Nordlux UK$Item Ledger Entry].[Item No_]
WHERE [Nordlux UK$Sales Price].[Sales Code] = 'DUN02'
GROUP BY [Nordlux UK$Item].No_

【问题讨论】:

标签: sql tsql group-by


【解决方案1】:

您需要在 group by 子句中添加 [Nordlux UK$Item].[Description] - 因为除了聚合函数之外的选择列表的每一列都应该是 group by 子句

SELECT
    [Nordlux UK$Item].No_,
    [Nordlux UK$Item].[Description],
    SUM([Nordlux UK$Item Ledger Entry].[Quantity]) AS Int
FROM [Nordlux UK$Item]
JOIN [Nordlux UK$Sales Price]
    ON [Nordlux UK$Item].[No_] = [Nordlux UK$Sales Price].[Item No_]
JOIN [Nordlux UK$Item Ledger Entry]
    ON [Nordlux UK$Item].[No_] = [Nordlux UK$Item Ledger Entry].[Item No_]
WHERE [Nordlux UK$Sales Price].[Sales Code] = 'DUN02'
GROUP BY [Nordlux UK$Item].No_, [Nordlux UK$Item].[Description]

【讨论】:

    【解决方案2】:

    在 select 语句中与其他列一起使用聚合函数时,通常使用 group by 并将 select 语句中的所有字段添加到 group by 中,聚合函数除外。

    在您的情况下,您应该使用: GROUP BY [Nordlux UK$Item].No_, [Nordlux UK$Item].[描述],

    如果您在 select 语句中仅使用聚合函数,则无需添加 group by 子句。

    【讨论】:

      【解决方案3】:

      使用聚合函数时,我总是按所有聚合列(即不使用 SUM、MAX、MIN、COUNT 等聚合函数的列)分组。

      SQL 不是一门年轻的语言,您可能想跳过一些聚合列,但我从来没有遇到过这种情况。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-19
        • 1970-01-01
        • 2017-08-08
        • 2012-09-18
        • 1970-01-01
        相关资源
        最近更新 更多