加入三个查询后,在sql server中没有得到正确的结果

时间:2014-03-27 12:21:09

标签: sql sql-server

我有三个这样的查询:

select count(*) as receved from transaction_tbl where locid=6 and status=0 
Result 
receved 
3

select count(*) as parked  from transaction_tbl where locid=6 and status=2
result 
parked  
48

select count(*) as requested from transaction_tbl where locid=6 and status=3
result
requested 
5

我想加入这三个查询,所以我写了这样的查询:

select count(*) as receved,count(*) as parked,count(*) as requested 
from transaction_tbl where locid=6 and status in(0,2,3) group by status

但现在我的结果是这样的

receved     parked      requested
----------- ----------- -----------
3           3           3
5           5           5
48          48          48

我尝试这样查询:

select count(*) as receved, count(*) as parked, count(*) as requested 
from transaction_tbl
where locid = 6 and status in (0,2,3);

但这次也得到了错误的结果: 如果有任何帮助非常明显:

我想要这样回答:

 receved     parked      requested
 ----------- ----------- -----------
3             48           5

所以我可以重新编写查询

2 个答案:

答案 0 :(得分:2)

也许是这样的:

select sum(status_receved) as receved, sum(status_parked) as parked, sum(status_requested) as requested from (select case when (status = 0) then 1 else 0 end as status_receved,
case when (status = 2) then 1 else 0 end as status_parked, 
case when (status = 3) then 1 else 0 end as status_requested 
from transaction_tbl where locid = 6 and status in (0,2,3)) a;

答案 1 :(得分:1)

如果要在输出中输入一行,请删除group by语句。这将是一个聚合查询,将整个表视为一个组并返回一行:

select count(*) as receved, count(*) as parked, count(*) as requested 
from transaction_tbl
where locid = 6 and status in (0,2,3);