选择多列分组?

时间:2011-04-20 18:25:58

标签: sql sql-server-2008

有人可以帮我解决这个问题吗?

    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_client的最近日期的Id_Eval

3 个答案:

答案 0 :(得分: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 :(得分:2)

如果您只想要ID_EVAL的最高ID_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

答案 2 :(得分:0)

此方法允许MAX(ID_EVAL)MAX(EVALUATION_CLIENT.Date)

不在同一行

如果您不必担心这种情况,请使用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