Sql server 按id查询表,如果不存在,请选择默认值
我有一个具有以下结构的表: 我想检索与特定ProductId和ReportType匹配的所有行。现在是踢球者。并非所有ReportType/TextBockType组合的所有ProductID都存在。但是,始终存在ProductId为0的值。ProductId为0表示默认值 换句话说:如果不存在具有特定ProductId/ReportType/TextBlockType的行,我希望返回具有ProductId 0的ReportType/TextBlockType组合的行Sql server 按id查询表,如果不存在,请选择默认值,sql-server,tsql,Sql Server,Tsql,我有一个具有以下结构的表: 我想检索与特定ProductId和ReportType匹配的所有行。现在是踢球者。并非所有ReportType/TextBockType组合的所有ProductID都存在。但是,始终存在ProductId为0的值。ProductId为0表示默认值 换句话说:如果不存在具有特定ProductId/ReportType/TextBlockType的行,我希望返回具有ProductId 0的ReportType/TextBlockType组合的行 一个人该怎么做呢?这是一
一个人该怎么做呢?这是一个多么可怕的问题!假设您正在寻找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