下面的代码获取了我的右侧行,但是我只想返回一个值,而不必在其上放置更多(任何)CASE。我可以重新检查该行中的两个值中的哪一个是最低的,但是我所寻找的实际值在现实世界中并不是按字母顺序排列的。'从而为它们分配价值。
如果我找回最低的字段文本或CASE编号,即理想的20。我不知道下一步该去哪里,没有重新检查这两个字段。
代码:
DECLARE @ID INT = '1234';
WITH GetMyInfo AS
(
SELECT field1, field2 , ID
, ROW_NUMBER() OVER (PARTITION BY ID,NAME ORDER BY CASE
WHEN ISNULL(field1, field2) = 'z' THEN 20
WHEN ISNULL(field1, field2) = 'b' THEN 10
WHEN ISNULL(field1, field2) = 't' or ISNULL(field1, field2) = 'f' THEN 0
ELSE 20
END) [RowNumber]
FROM TABLE
WHERE
(field1 IS NOT NULL OR field2 IS NOT NULL)
AND ID= @ID
)
SELECT field, field2
FROM GetMyInfo
WHERE RowNumber = 1
我喜欢Return RowNumberValue
之类的东西答案 0 :(得分:1)
WITH GetMyInfo AS (
SELECT t.*, field,
ROW_NUMBER() OVER (PARTITION BY ID, NAME
ORDER BY (CASE WHEN field = 'z' THEN 20
WHEN field = 'b' THEN 10
WHEN field in ('t', 'b') THEN 0
WHEN field is null THEN 100
ELSE 20
END)) [RowNumber]
FROM TABLE t CROSS APPLY
(VALUES (field1), (field2)) as v(field)
WHERE (field1 IS NOT NULL OR field2 IS NOT NULL) AND ID= @ID
)
SELECT field
FROM GetMyInfo
WHERE RowNumber = 1;
这会使数据无法显示,因此您只能返回匹配值。
答案 1 :(得分:1)
你可以使用一个额外的查询来实现你想要的东西
DECLARE @ID INT = '1234';
WITH GetMyInfo AS
(
SELECT field1,field2,caseNumber,ROW_NUMBER() OVER (PARTITION BY ID,NAME
ORDER BY [caseNumber] )[RowNumber]
FROM
(SELECT field1, field2 , ID,NAME
, CASE
WHEN ISNULL(field1, field2) = 'z' THEN 20
WHEN ISNULL(field1, field2) = 'b' THEN 10
WHEN ISNULL(field1, field2) = 't' or ISNULL(field1, field2) = 'f'
THEN 0
ELSE 20
END) [caseNumber]
FROM TABLE
)A
WHERE
(field1 IS NOT NULL OR field2 IS NOT NULL)
AND ID= @ID
)
SELECT field, field2,caseNumber
FROM GetMyInfo
WHERE RowNumber = 1