获取具有连接列的MAX值的整个ROW

时间:2011-07-14 19:03:22

标签: sql sql-server sql-server-2005 tsql greatest-n-per-group

我已经筋疲力尽地解决了这个问题,所以我将挑战带给你:

--CREATING DATA:

DECLARE @CONTACTS TABLE (ID INT, NickName CHAR(10))
INSERT INTO @CONTACTS VALUES (1359,'John Smith')
INSERT INTO @CONTACTS VALUES (1360,'Ana Keller')
INSERT INTO @CONTACTS VALUES (1361,'Joshua Doe')

DECLARE @ENTERPRISES TABLE (ID INT, CON_ID INT, ASSOCIATION DATETIME)
INSERT INTO @ENTERPRISES VALUES (123,1359,Convert(datetime, '2000-10-09', 120))
INSERT INTO @ENTERPRISES VALUES (123,1360,Convert(datetime, '2000-02-21', 120))
INSERT INTO @ENTERPRISES VALUES (123,1361,Convert(datetime, '2000-04-09', 120))

--QUERYING THE DATA:
SELECT * FROM @CONTACTS C
JOIN @ENTERPRISES E ON C.ID = E.CON_ID

--THE RESULT SET OF MY DREAMS:
    1359    John Smith    123    1359    2000-10-09

我想要的是之前查询的整行,但只有每个企业ID具有最大ASSOCIATION日期的那一行。这只是为了清晰起见的一个例子,我的真实查询要复杂得多,列数和数万亿行。我试过了

SELECT *,max(FOUNDING) OVER (PARTITION BY E.ID) FROM @CONTACTS C
JOIN @ENTERPRISES E ON C.ID = E.CON_ID

但它仍然带来了所有三行。其他方法更糟糕,导致解析器问我每列的GROUP BY。我感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

WITH cteMaxAssociation AS (
    SELECT ID, CON_ID, ASSOCIATION,
           ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ASSOCIATION DESC) AS RowNum
        FROM @ENTERPRISES
)
SELECT C.ID, C.NickName, ma.ID, ma.CON_ID, ma.ASSOCIATION
    FROM @CONTACTS C
        INNER JOIN cteMaxAssociation ma
            ON C.ID = ma.CON_ID
                AND ma.RowNum = 1

答案 1 :(得分:0)

SELECT *
FROM  @CONTACTS C
JOIN @ENTERPRISES E ON C.ID = E.CON_ID 
   (SELECT max(association) as maxdate, CON_ID , ID, ASSOCIATION 
     FROM Entpresises
     GROUP BY CON_ID ) maxresults
WHERE E.ID = maxresults.ID
AND E.ASSOCIATION = maxresults.ASSOCIATION ;