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

时间:2016-06-11 16:16:49

标签: sql sql-server tsql

我想根据列的具体状态分配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"有效,但是这样我必须对每个不同的状态进行相同的查询,是否有可能重用该查询或以某种方式基于{的输出变量的子查询赋值{1}}

以防我的代码示例有点乱(只是从内存中写一些),我想要做的是,计算有多少列具有特定状态并适合时间范围。

我已经完成了我需要的工作,在存储过程中有多个这样的查询,但我不想这样做。

2 个答案:

答案 0 :(得分:3)

您可以将查询编写为单个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;

答案 1 :(得分:0)

你想要这样的东西吗?

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

结果将使用一个查询输出到变量。

相关问题