有人可以告诉我如何在t-SQL的下一个CASE
语句中使用CASE
语句的输出作为输入吗?
exampleTable
id | itemNo | samplesLeft
-------------------------
1 | 001 | 104
2 | 003 | 53
3 | 002 | 193
4 | 001 | 32
我想要一个返回所有这些的查询,以及一个告诉它是否是工厂生成错误的布尔值。如果使用的样本少于十个,则错误被视为工厂出生。我的想法是首先使用CASE
创建一个列,显示已使用了多少样本,如下所示:
查询
SELECT
id,
itemNo,
samplesLeft,
CASE
WHEN itemNo= 001
THEN 200 - samplesLeft
WHEN itemNo= 002
THEN 300 - samplesLeft
WHEN itemNo= 003
THEN 400 - samplesLeft
ELSE 100 - samplesLeft
END AS samplesUsed
FROM exampleTable
然后我想在另一个CASE
中使用samplesUsed作为输入,来制作一个名为factoryError
的布尔值。如果samplesUsed < 10
,则说明为TRUE。怎么做?
答案 0 :(得分:1)
这是一种不好的方法,但是如果你有一个包含起始样本数量信息的列,你可以修复查询并使其更好......但这里有一种方法可以得到你想要的东西
create table #TempTableSam (itemNo nvarchar(5), samplesLeft int)
insert into #TempTableSam (itemNo, samplesLeft)
values ('001',50),('002',10),('003',20), ('004',80)
select itemNo, samplesLeft,
case
WHEN itemNo = '001' and 200 - samplesLeft < 190 then 'More than 10 samples has been used'
WHEN itemNo = '002' and 300 - samplesLeft < 280 then 'More than 10 samples has been used'
WHEN itemNo = '003' and 200 - samplesLeft < 190 then 'More than 10 samples has been used'
WHEN itemNo = '004' and 200 - samplesLeft < 190 then 'More than 10 samples has been used'
else 'Less then 10 samples has been used'
END as UsedSamples
from #TempTableSam
输出将是这样的
itemNo samplesLeft UsedSamples
001 50 More than 10 samples has been used
002 10 Less then 10 samples has been used
003 20 More than 10 samples has been used
004 80 More than 10 samples has been used
答案 1 :(得分:1)
您可以使用子查询执行此操作,例如
select
x.*,
case
when samplesUsed < 10 then 'Error'
else 'right'
end as status
from (
select
t.*,
CASE
WHEN itemNo = 001 THEN 200 - samplesLeft
WHEN itemNo = 002 THEN 300 - samplesLeft
WHEN itemNo = 003 THEN 400 - samplesLeft
ELSE 100 - samplesLeft
END AS samplesUsed
from tbl
) x
答案 2 :(得分:1)
您可以将您的工作查询作为CTE并继续下面...
WITH YourSELECTasCTE AS
(
SELECT
id,
itemNo,
samplesLeft,
CASE
WHEN itemNo= 001
THEN 200 - samplesLeft
WHEN itemNo= 002
THEN 300 - samplesLeft
WHEN itemNo= 003
THEN 400 - samplesLeft
ELSE 100 - samplesLeft
END AS samplesUsed
FROM exampleTable
)
SELECT * --do whatever you want here
FROM YourSELECTasCTE
答案 3 :(得分:1)