2014-03-27 48 views
0

我有三個查詢是這樣的:連接三個查詢後沒有得到在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 

和我trye這樣的查詢:

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

也許是這樣的:

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; 
+0

是的先生,這是工作正常..感謝您的幫助..應該非常感謝您滿意 – user3106114

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); 
+0

先生等,同時執行此得到錯誤的結果...... – user3106114

+0

我怎麼能解決這個問題 – user3106114