T-SQL从子查询中获取多个SUM

时间:2017-12-10 16:27:53

标签: sql-server tsql

这是我对这个论坛的第一个问题。我一直在寻找答案,但我没有找到类似的问题。

这是我的SQL Server表中的示例数据:

typ field1  field2  field3
--------------------------
IN  johny   bravo   123
IN  mickey  mouse     5
IN  mickey  mouse    70
OUT johny   bravo    20
OUT mickey  mouse    15

我需要选择的是:

field1  | field2    |   sum(field3) where typ='IN'  |   sum(field3) where typ='OUT'

这就是我到目前为止所提出的:

SELECT
    t.field1,
    t.field2,
    SUM(t1.total) AS total_in
    SUM(t2.total) AS total_out
FROM
(
    SELECT
        'IN' as typ,
        field1,
        field2,
        SUM(field3) AS total
    FROM XYZ
    LEFT JOIN some_table ON ...
    WHERE condition=1
    GROUP BY typ, field1, field2

    UNION ALL

    SELECT
        'OUT' as typ,
        field1,
        field2,
        SUM(field3) AS total
    FROM XYZ
    LEFT JOIN some_table ON ...
    WHERE condition=2
    GROUP BY typ, field1, field2
) t
LEFT JOIN t t1 ON t.field1 = t1.field1
LEFT JOIN t t2 ON t.field1 = t2.field1
GROUP BY 
    t1.field1,
    t1.field2

但是当我运行此查询时出现错误

  

Msg 206,Level 16,State 1,Line 1
  无效的对象名称t

我根本不知道如何让这个查询起作用。

我将非常感谢您的建议。感谢。

1 个答案:

答案 0 :(得分:1)

您想要条件聚合:

SELECT t.field1,  t.field2,
       SUM(CASE WHEN type = 'IN' THEN field3 ELSE 0 END) AS total_in,
       SUM(CASE WHEN type = 'OUT' THEN field3 ELSE 0 END) AS total_out
FROM . . .
GROUP BY t.field1, t.field2;

您也可以使用pivot

执行此操作