0

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

谢谢

例子:

积极的:

*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

4 回答 4

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
于 2013-08-08T20:09:01.603 回答
2

因此,您需要从 ACTIVE [下面的 UNION 的第一部分 [] 中获取所有内容,然后从 ARCHIVE [UNION 的第二部分 [。对于存档记录,排除那些不存在于 ACTIVE 表 [The 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)
于 2013-08-08T20:11:06.520 回答
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
于 2013-08-08T20:11:00.570 回答
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
于 2013-08-08T20:30:03.020 回答