我在SQL Server 2012
中有一个TransactionMaster表,它有唯一的TransactionID。 LowTransaction,MediumTransaction和HighTransaction表中将提供相同的TransactionID。
对于TransactionMaster中的每个TransactionID,我需要显示一个StatusMessage。 StatusMessage可能来自3个表中的任何一个 - 基于CRTDTEC
和CRTTIME
列中的日期...
SQL Server 2012
选择与最新日期对应的StatusMessage的最佳方法是什么?
注意:CRTDTEC格式 - YYMMDD
和CRTTIME格式 - HHMMSS
CODE
DECLARE @TransactionMaster TABLE (TransactionID INT)
DECLARE @LowTransaction TABLE (TransactionID INT, StatusMessage VARCHAR(80), CRTDTEC VARCHAR(8), CRTTIME VARCHAR(6))
DECLARE @MediumTransaction TABLE (TransactionID INT, StatusMessage VARCHAR(80), CRTDTEC VARCHAR(8), CRTTIME VARCHAR(6))
DECLARE @HighTransaction TABLE (TransactionID INT, StatusMessage VARCHAR(80), CRTDTEC VARCHAR(8), CRTTIME VARCHAR(6))
INSERT INTO @TransactionMaster VALUES (1)
INSERT INTO @TransactionMaster VALUES (2)
INSERT INTO @TransactionMaster VALUES (3)
INSERT INTO @LowTransaction VALUES (1,'1 Low','20131213','235959')
INSERT INTO @MediumTransaction VALUES (1,'1','20131213','235900')
INSERT INTO @HighTransaction VALUES (1,'1 High','20111213','235959')
INSERT INTO @LowTransaction VALUES (2,'2 Low','20111213','235959')
INSERT INTO @LowTransaction VALUES (3,'3 Low','20111213','235959')
INSERT INTO @MediumTransaction VALUES (3,'3 Medium','20111213','235959')
INSERT INTO @HighTransaction VALUES (3,'3 High','20140101','235959')
预期结果
(1,'1 Low','20131213','235959')
(2,'2 Low','20111213','235959')
(3,'3 High','20140101','235959')
答案 0 :(得分:2)
最简单的方法可能是
WITH TransConsolidated
AS (SELECT *
FROM @LowTransaction
UNION ALL
SELECT *
FROM @MediumTransaction
UNION ALL
SELECT *
FROM @HighTransaction)
SELECT TM.TransactionID,
CA.*
FROM @TransactionMaster TM
CROSS APPLY (SELECT TOP 1 *
FROM TransConsolidated TC
WHERE TC.TransactionID = TM.TransactionID
ORDER BY CRTDTEC DESC,
CRTTIME DESC) CA
或者另一种可能性(如果所有表上都有TransactionID
排序的覆盖索引)将合并所有四个表的连接
;WITH CTE
AS (SELECT TM.TransactionID,
MAX(CA.CRTDTEC + CA.CRTTIME + CA.StatusMessage) AS MaxRow
FROM @TransactionMaster TM
LEFT MERGE JOIN @LowTransaction LT
ON LT.TransactionID = TM.TransactionID
LEFT MERGE JOIN @MediumTransaction MT
ON MT.TransactionID = TM.TransactionID
LEFT MERGE JOIN @HighTransaction HT
ON HT.TransactionID = TM.TransactionID
CROSS APPLY (SELECT LT.*
UNION ALL
SELECT MT.*
UNION ALL
SELECT HT.*) CA
GROUP BY TM.TransactionID)
SELECT TransactionID,
SUBSTRING(MaxRow, 1, 8),
SUBSTRING(MaxRow, 9, 6),
SUBSTRING(MaxRow, 16, 80)
FROM CTE
答案 1 :(得分:0)
我猜你可以这样做......
SELECT TransactionID, StatusMessage, CRTDTEC, CRTTIME
FROM
(
SELECT *, rn = ROW_NUMBER() OVER (PARTITION BY TransactionID ORDER BY CRTDTEC DESC)
FROM
(
SELECT * FROM @LowTransaction
UNION ALL
SELECT * FROM @MediumTransaction
UNION ALL
SELECT * FROM @HighTransaction
)q
) q2
WHERE rn = 1
结果集
TransactionID StatusMessage CRTDTEC CRTTIME
1 1 Low 20131213 235959
2 2 Low 20111213 235959
3 3 High 20140101 235959