2014-02-13 38 views
1

我有一個表結構如下:查詢表,並選擇默認值,如果不存在

enter image description here

我想檢索所有匹配特定的產品編號和REPORTTYPE的行。現在這裏是踢球者。並非所有的ProductIds都存在於所有的ReportType/TextBockType組合中。但是,ProductId爲0時總是有值.0的ProductId表示默認值的值。

換句話說:如果有一排特殊產品編號/ REPORTTYPE/TextBlockType不存在,我想與REPORTTYPE/TextBlockType組合返回一行0產品編號

如何將一個去這樣做?

回答

1

真是個好問題!假設您正在查找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