真是個好問題!假設您正在查找ProductID = 20並且ReportType = 35和TextBlockType = 102.如果ProductID = 20不存在並且您將接受默認值0,則此模型可能有所幫助:
DECLARE @MyTable TABLE
(
ProductID int,
ReportType int,
TextBlockType int,
TextBlock nvarchar(MAX)
)
INSERT @MyTable (ProductID, ReportType, TextBlockType, TextBlock) VALUES (10,15,100,'abc')
INSERT @MyTable (ProductID, ReportType, TextBlockType, TextBlock) VALUES (0,15,100,'cba')
INSERT @MyTable (ProductID, ReportType, TextBlockType, TextBlock) VALUES (0,25,102,'abc')
INSERT @MyTable (ProductID, ReportType, TextBlockType, TextBlock) VALUES (0,25,102,'abc')
-- Comment | Uncomment to test receipt of record with ProductID = 20 or ProductID = 0
--INSERT @MyTable (ProductID, ReportType, TextBlockType, TextBlock) VALUES (20,35,102,'def')
INSERT @MyTable (ProductID, ReportType, TextBlockType, TextBlock) VALUES (0,35,102,'def')
INSERT @MyTable (ProductID, ReportType, TextBlockType, TextBlock) VALUES (0,35,102,'ghi')
INSERT @MyTable (ProductID, ReportType, TextBlockType, TextBlock) VALUES (0,35,102,'jkl')
;WITH temp AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY ReportType, TextBlockType ORDER BY ProductID DESC) AS rownumber
FROM @MyTable
)
SELECT *
FROM temp
WHERE rownumber = 1 and (ProductID = 20 or ProductID = 0) And ReportType = 35 And TextBlockType = 102