SQL求和字段并选择一列(带条件)并求和另一列

时间:2013-06-17 15:51:12

标签: sql tsql group-by sum conditional-statements

我有一个选择声明:

  SELECT ID, A, B, C, D
    FROM MyTable
GROUP BY ID, A, B, C, D
  HAVING D >= '14/06/2013'
     AND D <= '17/06/2013'

显示:

ID   |    A   |    B    |   C   |     D   
--------------------------------------------
11   |  1370  |    0    |  0    |  14/06/2013
11   |  1370  |   100   |  0    |  15/06/2013
11   |  1470  |   400   |  0    |  16/06/2013
11   |  1870  |    0    | 300   |  17/06/2013

我希望结果是:

ID   | min of D|  Sum(B) |  Sum(C) |  max of D|   MIN(D)
11   |  1370   |   500   |   300   |   1870   |  14/06/2013

如何在SQL Server上执行此操作

2 个答案:

答案 0 :(得分:2)

这是一种方法(假设SQL Server 2005 +):

;WITH CTE AS
(
    SELECT  *,
            RN1 = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY D DESC),
            RN2 = ROW_NUMBER() OVER(PARTITION BY ID ORDER BY D)
    FROM YourTable
    WHERE D >= '20130614'
    AND D <= '20130617'
)
SELECT  ID,
        MIN(CASE WHEN RN2 = 1 THEN A END) [min of D],
        SUM(B) [Sum(B)],
        SUM(C) [Sum(C)],
        MIN(CASE WHEN RN1 = 1 THEN A END) [max of D],
        MIN(D) [Min(D)]
FROM CTE
GROUP BY ID

结果:

╔════╦══════════╦════════╦════════╦══════════╦════════════╗
║ ID ║ MIN OF D ║ SUM(B) ║ SUM(C) ║ MAX OF D ║  MIN(D)    ║
╠════╬══════════╬════════╬════════╬══════════╬════════════╣
║ 11 ║     1370 ║    500 ║    300 ║     1870 ║ 2013-06-14 ║
╚════╩══════════╩════════╩════════╩══════════╩════════════╝

here is an sqlfiddle及其演示。

答案 1 :(得分:1)

你可以通过JOIN

来做到这一点
SELECT  T.ID ,
        MAX(G.B) AS [SUM(B)],
        MAX(G.C) AS [SUM(C)],
        MAX(MINI)AS [MIN(D)] ,
        MAX(CASE WHEN T.D = G.MINI THEN T.A ELSE NULL END ) AS [MIN OF D],
        MAX(CASE WHEN T.D = G.MAXI THEN T.A ELSE NULL END ) AS [MAX OF D]
FROM    TEST T
JOIN    ( SELECT ID , SUM(B) B ,SUM(C) C ,MIN(D) AS MINI ,MAX(D) AS MAXI
          FROM  test 
          WHERE D >= '06/14/2013'
             AND D <= '06/17/2013'
          GROUP BY  ID ) G ON G.ID = T.ID
GROUP BY T.ID

SQL小提琴演示HERE