2011-04-20 77 views
4

有人可以幫我看看這個查詢嗎?選擇多列一組?

SELECT CLIENT.ID_CLIENT , 
      EVALUATION_CLIENT.ID_EVAL , 
      MAX(EVALUATION_CLIENT.Date) AS DATE 

FROM EVALUATION_CLIENT 

INNER JOIN CLIENT 
    ON CLIENT.ID_CLIENT = EVALUATION_CLIENT.FK_IDClient 

WHERE EVALUATION_CLIENT.Date 
      BETWEEN @START_DATE_LOCAL 
      AND @END_DATE_LOCAL 

GROUP BY CLIENT.IDCLIENT, 
      EVALUATION_CLIENT.ID_EVAL 

它返回......

ID_CLIENT | ID_EVAL | DATE_EVAL 
1423  |11160  | 2008-02-12 00:00:00.000 
1423  |11161  | 2008-02-18 00:00:00.000 
18  |11162  | 2008-02-15 00:00:00.000 
666  |11163  | 2008-02-19 00:00:00.000 

但我想是這樣(不重複的客戶端)

ID_CLIENT | ID_EVAL | DATE_EVAL 
1423  |11161  | 2008-02-18 00:00:00.000 
18  |11162  | 2008-02-15 00:00:00.000 
666  |11163  | 2008-02-19 00:00:00.000 

我使用MSSQL 2008

感謝了很多!

更新:我需要Id_Eval爲最近的日期由Id_client

+0

你只是想爲每個客戶提供最高的ID_EVAL嗎?或者你想要最新的日期?這些定義是否一樣? – 2011-04-20 18:32:38

回答

5

如果你只想要最新的條目爲每個客戶端,你可以使用:

;WITH ClientEvals AS 
(
    SELECT 
     c.ID_CLIENT , 
     e.ID_EVAL , 
     e.Date AS ClientDATE, 
     ROW_NUMBER() OVER(PARTITION BY c.ID_CLIENT ORDER BY e.Date DESC) AS 'RowNo' 
    FROM  
     dbo.EVALUATION_CLIENT e 
    INNER JOIN 
     dbo.CLIENT c ON c.ID_CLIENT = e.FK_IDClient 
    WHERE 
     e.Date BETWEEN @START_DATE_LOCAL AND @END_DATE_LOCAL 
) 
SELECT  
    ID_CLIENT , 
    ID_EVAL , 
    ClientDATE 
FROM 
    ClientEvals 
WHERE 
    RowNo = 1 

的CTE(公共表表達式)內的內選擇選擇evals爲每一個客戶,和分區ID_Client的數據 - 每個客戶端從1開始獲取行數,其中1是最近的條目。

外部SELECT基於CTE,並且僅選擇那些具有RowNo = 1的行 - >每個客戶端的最新行。

+1

使用不錯的ROW_NUMBER – 2011-04-20 18:31:33

+0

這正是我想要做的!謝謝 – 2011-04-20 19:02:22

2

你可以做以下的,如果你只是想最高ID_EVALID_CLIENT

SELECT CLIENT.ID_CLIENT , 
      MAX(EVALUATION_CLIENT.ID_EVAL), 
      MAX(EVALUATION_CLIENT.Date) AS DATE 

FROM EVALUATION_CLIENT 

INNER JOIN CLIENT 
    ON CLIENT.ID_CLIENT = EVALUATION_CLIENT.FK_IDClient 

WHERE EVALUATION_CLIENT.Date 
      BETWEEN @START_DATE_LOCAL 
      AND @END_DATE_LOCAL 

GROUP BY CLIENT.IDCLIENT 
+0

請注意,這可能會從一行返回'ID_EVAL',而從另一行返回'Date'。這可能沒什麼問題,因爲海報並不清楚這些要求 - 但它們似乎更有可能同時擁有這兩個要素。如果保證更高的'ID_EVAL'也會有一個更晚的'Date',那麼在任何情況下都可以。 – 2011-04-20 18:34:06

+0

@Dave - 真夠的。需要來自OP的更多信息來確定。 – Oded 2011-04-20 18:46:39

0

這種方法將允許案例MAX(ID_EVAL)MAX(EVALUATION_CLIENT.Date)不在同一行

如果您不必擔心這種情況se Oded的方法。

SELECT CLIENT.ID_CLIENT , 
     EVALUATION_CLIENT.ID_EVAL , 
     EVALUATION_CLIENT.Date 
FROM evaluation_client 
     INNER JOIN client 
     ON client.id_client = evaluation_client.fk_idclient 
     INNER JOIN (SELECT client.id_client, 
          MAX(evaluation_client.DATE) AS DATE 
        FROM evaluation_client 
          INNER JOIN client 
          ON client.id_client = evaluation_client.fk_idclient 
        WHERE evaluation_client.DATE BETWEEN 
          @START_DATE_LOCAL AND @END_DATE_LOCAL 
        GROUP BY client.id_client, 
          evaluation_client.id_eval)maxdate 
     ON evaluation_client.DATE = maxdate.DATE 
      AND client.id_client = maxdate.id_client