递归聚合SQL列

时间:2014-03-06 23:32:44

标签: sql sql-server join aggregate-functions

我有两个表,我正在尝试构建一个查询,该查询将JOINSUM所有数字列(盈利/亏损),然后再次SUM所有利润和所有损失。

也许我的桌子设计很差 - 任何指导都是适用的。

现在,我有:

表:公司

C_ID  |  NAME
-------------------
 1    |  Abc

表:财务

ID  |  COMPANY_ID  |  INCOME1  |  INCOME2  | COST1  |  COST2
------------------------------------------------------------
1          1            200
2          1                        50
3          1                                   5
4          1                                   3
5          1                                             40

我正在寻找的输出类似于(其中CASH的固定起始值为100)

C_ID  |  NAME  |  INCOME1  |  INCOME2  | COST1  |  COST2  |  CASH
------------------------------------------------------------------
 1       Abc       200          50         8        40       302

我尝试了什么:

SELECT
    C.C_ID, C.NAME,
    SUM(F.INCOME1), SUM(F.INCOME2),
    SUM(F.COST1), SUM(F.COST2),
    (100 +
            (SELECT SUM(F.INCOME1), SUM(F.INCOME2) FROM FINS F)
          - (SELECT SUM(F.COST1), SUM(F.COST2) FROM FINS F)
    )
FROM COMP C
INNER JOIN FINS F
ON C.C_ID = F.COMPANY_ID
GROUP BY C.C_ID, C.NAME

2 个答案:

答案 0 :(得分:1)

测试数据

DECLARE @Company TABLE(C_ID INT,NAME VARCHAR(10))
INSERT INTO @Company VALUES
(1,'Abc')

DECLARE @FINANCIAL TABLE
(ID INT,COMPANY_ID INT,INCOME1 INT,INCOME2 INT,COST1 INT,COST2 INT)
INSERT INTO @FINANCIAL VALUES
(1,1,200,NULL,NULL,NULL),
(2,1,NULL,50 ,NULL,NULL),
(3,1,NULL,NULL,  5,NULL),
(4,1,NULL,NULL,  3,NULL),
(5,1,NULL,NULL,NULL,40)

<强>查询

SELECT *, INCOME1+INCOME2-COST1-COST2 AS CASH
FROM (
SELECT  C.C_ID
       ,C.NAME
       ,SUM(F.INCOME1) AS INCOME1
       ,SUM(F.INCOME2) AS INCOME2
       ,SUM(F.COST1)   AS COST1
       ,SUM(F.COST2)   AS COST2
FROM @Company C INNER JOIN @FINANCIAL F
ON C.C_ID = F.COMPANY_ID
GROUP BY C.C_ID
       ,C.NAME
      ) Q

结果集

╔══════╦══════╦═════════╦═════════╦═══════╦═══════╦══════╗
║ C_ID ║ NAME ║ INCOME1 ║ INCOME2 ║ COST1 ║ COST2 ║ CASH ║
╠══════╬══════╬═════════╬═════════╬═══════╬═══════╬══════╣
║    1 ║ Abc  ║     200 ║      50 ║     8 ║    40 ║  202 ║
╚══════╩══════╩═════════╩═════════╩═══════╩═══════╩══════╝

Working SQL FIDDLE

答案 1 :(得分:0)

尝试这个

SELECT C.C_ID, C.NAME, F.INCOME1, F.INCOME2, F.COST1, F.COST2, ((100 + F.INCOME1 + F.INCOME2) - (F.COST1 + F.COST2)) AS CASH
FROM COMPANY C
INNER JOIN
(
    SELECT COMPANY_ID, SUM(INCOME1) AS INCOME1, SUM(INCOME2) AS INCOME2
    , SUM(COST1) AS COST1, SUM(COST2) AS COST2
    FROM FINANCIAL
    GROUP BY COMPANY_ID
) F ON C.C_ID = F.COMPANY_ID