按行求和,而不是整个查询

时间:2018-08-02 11:03:18

标签: sql-server sql-server-2008-r2

使用以下查询:

SELECT
    ACT_CODE,
    ORL_EVENT,
    ACT_NOTE,
    (SUM(ORL_PRICE*ORL_ORDQTY)) AS 'ORD_TOTAL'
FROM
    R5ORDERLINES 
INNER JOIN
    R5ACTIVITIES on ACT_EVENT = ORL_EVENT
WHERE
    ORL_EVENT = '123'
GROUP BY 
    ACT_CODE, ORL_EVENT, ACT_NOTE
ORDER BY 
    ACT_ACT

当我需要每个ACT_CODE的总计(所有房屋,所有汽车等的总计)而不是所有产品的总计时,我得到这样的结果,其中ORD_TOTAL是所有行的总和。

+--------+---------+-----------+----------+
|ACT_CODE|ORL_EVENT| ACT_NOTE  | ORD_TOTAL|
+--------+---------+-----------+----------+
|1110    |123      | Houses    | 2500     |
|1111    |123      | Cars      | 2500     |
|1112    |123      | TVs       | 2500     |
|1113    |123      | Computers | 2500     |
+--------+---------+-----------+----------+

实际上我需要像这样:

+--------+---------+-----------+----------+
|ACT_CODE|ORL_EVENT| ACT_NOTE  | ORD_TOTAL|
+--------+---------+-----------+----------+
|1110    |123      | Houses    | 1250     |
|1111    |123      | Cars      |  500     |
|1112    |123      | TVs       |  250     |
|1113    |123      | Computers |  500     |
+--------+---------+-----------+----------+

我尝试了很多查询修改,但似乎无济于事……而且我对此并不熟练。

1 个答案:

答案 0 :(得分:0)

使用PARTITION BY子句。我已经修改了如下查询。未测试,因为我没有数据。请检查并还原。

SELECT DISTINCT
    ACT_CODE,
    ORL_EVENT,
    ACT_NOTE,
    (SUM(ORL_PRICE*ORL_ORDQTY) OVER(PARTITION BY ACT_NOTE) AS 'ORD_TOTAL'
FROM
    R5ORDERLINES 
INNER JOIN
    R5ACTIVITIES on ACT_EVENT = ORL_EVENT
WHERE
    ORL_EVENT = '123'
ORDER BY 
    ACT_ACT