内在加入或还有什么?

时间:2014-07-23 08:17:31

标签: sql sql-server-2012

我有什么

Table A                                 Table B


ID    ID_Fruit    ,,, so on             ID      ID_Fruit   ID_CRATE  DateTime                
1     1002                              i_1     1002          1      2014-07-28 00:00.000
2     4534                              i_2     1002          2      2014-06-25 00:00.000
3     1243                              i_3     1243          NULL   2014-07-09 00:00.000
4     1003                              i_4     4534          1      2014-07-23 00:00.000

我想要的结果

ID    ID_Fruit    ,,, so on             ID      ID_Fruit    ID_CRATE     DateTime
1     1002                              i_1     1002           2      2014-06-25 00:00.000
2     4534                              i_4     4534           1      2014-07-23 00:00.000

我在尝试什么,

SELECT * FROM TABLEA
OUTER APPLY  
        (SELECT * FROM TableB WHERE TableB.ID_Fruit = TableA.ID_Fruit AND TableB.ID_CRATE IS NOT NULL) As Table_B

我希望基于closet DateTime

的表B中的几行中只有1行

4 个答案:

答案 0 :(得分:3)

写为

;with CTE as 
( Select ID,
         ID_Fruit,
         ID_CRATE,
         [DateTime],
         Row_number() over ( partition by ID_Fruit order by [DateTime]  desc) as rownum
         from Table_B
 ) 
 select A.ID,A.ID_Fruit,C.ID,C.ID_CRATE,C.[DateTime] 
 from CTE C
 join Table_A A on A.ID_Fruit = C.ID_Fruit
 where C.rownum = 1 and isnull(ID_CRATE,'') <> ''

Check Demo here..

答案 1 :(得分:0)

SELECT A.*, B.* FROM TABLE_A A, TABLE_B B
WHERE A.ID_Fruit = B.ID_Fruit
and B.DateTime IN (SELECT MAX(DateTime) from TABLE_B WHERE ID_Fruit = B.ID_Fruit)

答案 2 :(得分:0)

SELECT
    TableAID,
    TableAID_Fruit,
    TableBID,
    TableBID_Fruit,
    ID_CRATE,
    DateTime
FROM
    (SELECT 
        TableA.ID TableAID,
        TableA.ID_Fruit TableAID_Fruit,
        TableB.ID TableBID,
        TableB.ID_Fruit TableBID_Fruit,
        TableB.ID_CRATE,
        TableB.DateTime,
        ROW_NUMBER() OVER (PARTITION BY TableB.ID_Fruit ORDER BY TableB.DateTime DESC) TableBOrder
    FROM
        TableA
        INNER JOIN TableB ON TableA.ID_Fruit = TableB.ID_Fruit
    ) Results
WHERE
    TableBOrder = 1

答案 3 :(得分:0)

SELECT *
FROM TABLEA
CROSS APPLY
(
    SELECT TOP 1 *
    FROM TableB
    WHERE TableB.ID_Fruit = TableA.ID_Fruit
    AND TableB.ID_CRATE IS NOT NULL
    ORDER BY [DateTime]
) As Table_B

你使用OUTER APPLY在正确的轨道上,但是你将获得左表中的所有行,甚至是右表中没有匹配行的行,所以你可能想要使用CROSS APPLY(左行)没有返回右表中匹配的行。)

你只是忘了使用TOP 1和ORDER BY。

这是一篇关于每组TOP N行的好文章:http://sqlmag.com/database-development/optimizing-top-n-group-queries