按ID查询表,如果不存在则选择默认值

时间:2014-02-13 17:09:09

标签: sql-server tsql

我有一个具有以下结构的表:

enter image description here

我想检索与特定ProductId和ReportType匹配的所有行。现在这里是踢球者。并非所有ReportType / TextBockType组合都存在所有ProductIds。但是,ProductId为0时始终存在一个值.CroductId为0表示默认值。

换句话说:如果不存在具有特定ProductId / ReportType / TextBlockType的行,我想返回包含ProductId 0的ReportType / TextBlockType组合的行。

如何做到这一点?

1 个答案:

答案 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