简体   繁体   English

重用查询/子查询结果以根据列值分配多个输出

[英]Reusing query/subquery results to assign multiple outputs depending on a column value

I want to assign 4 output values based on specific status of a column, while counting how many occurrences of it there are. 我想根据列的特定状态分配4个输出值,同时计算它的出现次数。

For example 例如

   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 )

adding extra where statement such as and t2.status="somestatus" works, but this way I have to to same query for eachdifferent status I have, is it possible to reuse that query or somehow sub query assignment of output variables based on t2.status 添加额外的where语句,如t2.status="somestatus" ,但是这样我必须对t2.status="somestatus"不同的状态进行相同的查询,是否有可能重用该查询或以某种方式基于t2.status对输出变量进行子查询分配t2.status

Just in case my code example is bit messed up (just writing some from memory), what I am trying to do, is count how many columns there are with particular status and fits in time frame. 为了防止我的代码示例被搞砸了(只是从内存中写了一些),我想要做的是,计算有多少列具有特定状态并适合时间范围。

I've done what I need, by having multiple queries like this in stored procedure, but I don't want to keep it this way. 我已经完成了我需要的工作,在存储过程中有多个这样的查询,但我不想这样做。

You can write the query as a single select : 您可以将查询编写为单个select

Select @someVariable = count(*)
from table join
     table 2 as t2
     on r.id = t2.id 
where getdate() between t2.start and t2.end;

You can then add more variables easily: 然后,您可以轻松添加更多变量:

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;

Do you want something like this? 你想要这样的东西吗?

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

The results will output to variables using one query. 结果将使用一个查询输出到变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM