2014-03-24 75 views
-2

我有3個表 -SQL服務器:需要查詢

Table_1 
accid0v fcustn0v 

1210001  A 
1210002  B 
1210003  C 

Table_2 
accid0v cases0v 

1210001  Open 
1210001  Open 
1210001 Resolved 
1210002 Resolved 
1210003  Open 

Table_3 
accid0v  actd0v 

1210001  2/16/2014 
1210002  4/5/2014 
1210003  6/8/2014 

我想說明這樣

accid0v fcustn0v actd0v Total Open 

1210001 A  2/16/2014 3  2 
1210002 B  4/5/2014 1  0 
1210003 C  6/8/2014 1  1 

數據我使用SQL Server 2008

回答

1

一個相當簡單的JOINGROUP BY將做到這一點;

SELECT 
    a.accid0v, a.fcustn0v, c.actd0v, 
    COUNT(*) total, SUM(CASE WHEN b.cases0v='open' THEN 1 ELSE 0 END) [Open] 
FROM table_1 a 
JOIN table_2 b ON a.accid0v = b.accid0v 
JOIN table_3 c ON a.accid0v = c.accid0v 
GROUP BY a.accid0v, a.fcustn0v, c.actd0v 

An SQLfiddle to test with

+0

thanx Joachim Isaksson幫我... – user3441151

+0

我們可以做到這一點,而不使用SUM - CASE當......嗎?謝謝。 –

+0

@BoratSagdiyev有什麼特別的原因?有多種方法來編寫查詢,但我不太清楚你在找什麼。 –

0

這是我的第一次以爲

select 
    t1.accid0v 
    ,t1.fcustn0v 
    ,t3.actd0v 
    ,sum(case when t2.cases0v='Open' then 1 else 0 end) as open 
    ,sum(0) as total 
from table_1 as t1 
join table_2 as t2 on t2.accid0v=t1.accid0v 
join table_3 as t3 on t3.accid0v=t1.accid0v 
group by 1,2,3 
+0

您的'GROUP BY'語法不會(據我所知)在SQL Server上工作。 –

+0

@JoachimIsaksson - 我收到一個錯誤 - 關鍵字'open'附近的語法不正確。 –