显示两个表中的已排序数据集

时间:2013-08-08 20:00:22

标签: sql sql-server tsql

我正在尝试构建一个从活动和归档表中进行选择的视图,但只在活动文件夹中不存在该记录时才从归档文件夹中返回记录。它还必须仅返回具有最新时间戳的存档记录。

谢谢

示例:

有效

*ID  ItemID   Price*
1    001     1.00

2    002     4.99

3    004     2.00

存档

*ID ItemID   Price   ArchiveDate*

1    001    0.99    1/1/2013

2    002    3.78    1/1/2013

3    003    5.00    1/5/2013

4    005    3.49    1/5/2013

5    003    6.99    1/10/2013

应返回以下数据集

*ItemID Price*

001     1.00

002     4.99

003     6.99   <-- From Archive

004     2.00

005     3.49   <-- From Archive

4 个答案:

答案 0 :(得分:3)

您可以使用以下内容:

SELECT ItemID, Price
FROM 
(
-- All of the active records
SELECT ItemID, Price 
FROM Active 
UNION ALL    
-- combined with the latest archive records for missing actives
SELECT ItemID, Price 
FROM Archive AS A1
WHERE ArchiveDate=(SELECT MAX(ArchiveDate) 
                   FROM Archive AS A2
                   WHERE A2.ItemID=A1.ItemID)
      AND NOT EXISTS(SELECT 1 
                     FROM Active AS AC 
                     WHERE AC.ItemID=A1.ItemID)
) AS FinalResult
-- Ordered by ItemID
ORDER BY ItemID

答案 1 :(得分:2)

所以你需要从ACTIVE [下面的UNION的第一部分] [,然后追加ARCHIVE的记录[UNION的第二部分]。 对于存档记录,驱逐那些在ACTIVE表[NOT EXISTS子句]中不存在的记录,只获取具有最新日期[THE MAX(ArchiveDate)]子句的记录。

SELECT  ItemID
        ,Price
FROM    ACTIVE
UNION
SELECT  ItemID
        ,Price
FROM    ARCHIVE AA
WHERE   AA.ArchiveDate = (SELECT MAX(ArchiveDate) FROM ARCHIVE AA1 WHERE AA1.ItemID = AA.ItemID)
AND     NOT EXISTS (SELECT 1 FROM ACTIVE A WHERE A.ItemID = AA.ItemID)

答案 2 :(得分:0)

;with cte_archive as (
     select
         ItemID, Price,
         row_number() over (partition by ItemID order by ArchiveDate desc) as row_num
     from Archive 
)
select AC.ItemID, AC.Price
from Active as AC

union all

select AH.ItemID, AH.Price
from cte_archive as AH
where AH.ItemID not in (select ItemID from Active) and AH.row_num = 1

答案 3 :(得分:0)

SELECT ItemID, Price
FROM Active
UNION ALL
SELECT ItemID, Price
FROM (
    SELECT ItemID, Price
    FROM (
        SELECT ItemID, Price, 
               ROW_NUMBER() OVER(PARITION BY ItemID ORDER BY ArchiveDate DESC) rn
        FROM Archive
        WHERE NOT EXISTS(SELECT 1 FROM Active a WHERE a.ItemID = Active.ItemID)
    ) sub
    WHERE rn=1 
) Archive