[英]Reusing query/subquery results to assign multiple outputs depending on a column value
我想根據列的特定狀態分配4個輸出值,同時計算它的出現次數。
例如
Select @someVariable =(Select count(*) as r
from table
join table 2 as t2
on r.id= t2.id
where getdate() between t2.start and t2.end )
添加額外的where語句,如t2.status="somestatus"
,但是這樣我必須對t2.status="somestatus"
不同的狀態進行相同的查詢,是否有可能重用該查詢或以某種方式基於t2.status
對輸出變量進行子查詢分配t2.status
為了防止我的代碼示例被搞砸了(只是從內存中寫了一些),我想要做的是,計算有多少列具有特定狀態並適合時間范圍。
我已經完成了我需要的工作,在存儲過程中有多個這樣的查詢,但我不想這樣做。
您可以將查詢編寫為單個select
:
Select @someVariable = count(*)
from table join
table 2 as t2
on r.id = t2.id
where getdate() between t2.start and t2.end;
然后,您可以輕松添加更多變量:
Select @someVariable = count(*),
@someVariable2 = sum(case when t2.status = 'somestatus' then 1 else 0 end)
from table join
table 2 as t2
on r.id = t2.id
where getdate() between t2.start and t2.end;
你想要這樣的東西嗎?
SELECT
@TotalCount = count(*),
@Status1 = s1.status1,
@Status2 = s2.status2,
@Status3 = s3.status3
FROM [table]
CROSS JOIN (SELECT count(*) as status1 FROM [table] WHERE [status] = 'status1' and getdate() between [start] and [end]) s1
CROSS JOIN (SELECT count(*) as status2 FROM [table] WHERE [status] = 'status2' and getdate() between [start] and [end]) s2
CROSS JOIN (SELECT count(*) as status3 FROM [table] WHERE [status] = 'status3' and getdate() between [start] and [end]) s3
結果將使用一個查詢輸出到變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.