3

我在表格中有不同版本的费用。我想获取并汇总按类型分组的最后一笔费用。

所以我想添加 9.87、9.63、1.65。

我想要 Parent ID , sum(9.87 + 9.63 + 1.65) 作为这个查询的结果。

我们使用 MSSQL

ID  ORDER   CHARGES     TYPE    PARENT ID           
1   1       6.45        1       1
2   2       1.25        1       1
3   3       9.87        1       1
4   1       6.54        2       1
5   2       5.64        2       1
6   3       0.84        2       1
7   4       9.63        2       1
8   1       7.33        3       1
9   2       5.65        3       1
10  3       8.65        3       1
11  4       5.14        3       1
12  5       1.65        3       1
4

4 回答 4

4
WITH recordsList
AS
(
    SELECT Type, Charges,
            ROW_NUMBER() OVER (PArtition BY TYPE
                                ORDER BY [ORDER] DESC) rn
    FROM tableName
)
SELECT  SUM(Charges) totalCharge
FROM recordsLIst
WHERE rn = 1
于 2013-01-28T15:15:57.977 回答
3

用于row_number()标识要求和的行,然后对它们求和:

select SUM(charges)
from (select t.*,
             ROW_NUMBER() over (PARTITION by type order by id desc) as seqnum
      from t
     ) t
where seqnum = 1
于 2013-01-28T15:16:04.130 回答
1

或者,您可以使用窗口聚合MAX()

SELECT SUM(Charges)
FROM (
  SELECT
    [ORDER],
    Charges,
    MaxOrder = MAX([ORDER]) OVER (PARTITION BY [TYPE])
  FROM atable
) s
WHERE [ORDER] = MaxOrder
;
于 2013-01-28T17:27:31.523 回答
0
SELECT t.PARENT_ID, SUM(t.CHARGES)
FROM dbo.test73 t
WHERE EXISTS (
              SELECT 1
              FROM dbo.test73
              WHERE [TYPE] = t.[TYPE]
              HAVING MAX([ORDER]) = t.[ORDER]
              )
GROUP BY t.PARENT_ID

SQLFiddle上的演示

于 2013-01-28T21:39:04.750 回答