0

I have a select statement:

  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'

show this:

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

I Want the result is:

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

How do I do that on SQL Server

4

2 回答 2

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 ║
╚════╩══════════╩════════╩════════╩══════════╩════════════╝

这是一个带有演示的sqlfiddle 。

于 2013-06-17T16:06:51.937 回答
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 Fiddle 演示在这里

于 2013-06-17T16:22:51.767 回答