SQL代码SUM CASE语句

时间:2017-07-27 19:10:51

标签: sql sum case

我有一张表,我必须为每个订单上的每个客户计算特定零件号的订单数量。我收到了错误

"Column 'ALL_INFORMATION.CUSTOMER_ID' is invalid in the select list because
 it is not contained in either an aggregate function or the GROUP BY clause."

我不知道还能做什么。以下是我的代码。我感谢任何和所有的帮助。

WITH ALL_INFORMATION
    AS (SELECT CUSTOMER_ID, SO_ID, CHANGE_DATE, PART_ID, ORDER_QTY, PRODUCT_LINE FROM SOFBH),
PRODUCT_QUANTITY
AS (
    SELECT  *,
    sum(
        case when PART_ID = '3860+' then ORDER_QTY else 0
    end) as '3860+',
    sum(
        case when PART_ID = '3861' then ORDER_QTY else 0
    end) as '3861',
    sum(
        case when PART_ID = '3865' then ORDER_QTY else 0
    end) as '3865',
    sum(
        case when PRODUCT_LINE = '1055' then ORDER_QTY else 0
    end) as '1055',
    sum(
        case when PRODUCT_LINE = '1056' then ORDER_QTY else 0
    end) as '1056',
    sum(
        case when PRODUCT_LINE = '1057' then ORDER_QTY else 0
    end) as '1057',
    sum(
        case when PRODUCT_LINE = '1058' then ORDER_QTY else 0
    end) as '1058'
FROM ALL_INFORMATION)


select *
FROM ALL_INFORMATION
GROUP BY CUSTOMER_ID, SO_ID

4 个答案:

答案 0 :(得分:1)

你试图在一个查询中做太多的事情。我认为你应该采取的方法是创建一些临时表,使用主表/视图将所有数据拉到一起并总结所需的值。像这样:

创建表tmp3860(聚集,字段,这里) CREATE TABLE tmp3861(聚集,字段,这里) CREATE TABLE tmp3865(聚集,字段,这里)......

然后做一个UNION

SELECT * FROM tmp3860 UNION SELECT * FROM tmp3861 ...

并将其插入View或其他主临时表中。 然后在那个View或Master Temp表中做你的总和

答案 1 :(得分:0)

这是因为下面的SQL语句没有使用GROUP BY的任何聚合函数(SUM,AVG等)。

SELECT *
  FROM ALL_INFORMATION
 GROUP BY CUSTOMER_ID, SO_ID

是的,你在SQL中使用了SUM()函数,但没有使用GROUP BY的地方。

答案 2 :(得分:0)

如果您想在每个行上汇总,请使用窗口函数:

PRODUCT_QUANTITY as (
 SELECT  *,
         sum(case when PART_ID = '3860+' then ORDER_QTY else 0 end) over () as '3860+',

您需要为每个over ()添加sum()

答案 3 :(得分:0)

检查以下查询,我认为这就是您所需要的。

SELECT  CUSTOMER_ID, SO_ID,
sum(
    case when PART_ID = '3860+' then ORDER_QTY else 0
end) as '3860+',
sum(
    case when PART_ID = '3861' then ORDER_QTY else 0
end) as '3861',
sum(
    case when PART_ID = '3865' then ORDER_QTY else 0
end) as '3865',
sum(
    case when PRODUCT_LINE = '1055' then ORDER_QTY else 0
end) as '1055',
sum(
    case when PRODUCT_LINE = '1056' then ORDER_QTY else 0
end) as '1056',
sum(
    case when PRODUCT_LINE = '1057' then ORDER_QTY else 0
end) as '1057',
sum(
    case when PRODUCT_LINE = '1058' then ORDER_QTY else 0
end) as '1058'

FROM PRODUCT_QUANTITY GROUP BY CUSTOMER_ID, SO_ID