2013-01-07 74 views
1

首先,我的sql最多是粗糙的,所以請隨身攜帶。將一列中的值的實例總和爲不同的列

我有一個表,會議,其中有一個約會類型列(nvarchar)。 aptType可以是三個值之一(小時,半小時,一對)。

我需要的是clientname,小時數,halfhours數,pair數。

因此數據可能看起來像這樣

bob | Hour 
bob | Hour 
bob | halfhour 
bob | halfhour 
bob | halfhour 
bob | Pair 

我想什麼是

bob | 2 | 3 | 1 

我想變化這個主題

select c.firstname, 
count(shour.clientid), 
count(shalfhour.clientid), 
count(sHour.clientid) 
From Client as c 
       left outer join [session] as sHour on c.Entityid = shour.ClientId 
       left outer join [session] as sHalfHour on c.Entityid = sHalfHour.ClientId 
       left outer join [session] as sPair on c.Entityid = sPair.ClientId 
       where c.entityid =1 and (shour.appointmentType = 'Hour' or sHalfHour.appointmentType = 'HalfHour') 
       group by c.firstname 

數據客戶端1是他有35小時的apttypes和其餘的0。

當我做以上我得到

bob | 1135 | 1135 | 1135 

如果我改變了其中一個還是我得到0行回來。

有沒有辦法做我想做的事情?

感謝, [R

回答

2

這可以使用單個連接來完成,你轉動使用CASE語句聚合函數的數據:

select c.firstname, 
    SUM(case when s.appointmentType = 'Hour' then 1 else 0 end) Hour, 
    SUM(case when s.appointmentType = 'HalfHour' then 1 else 0 end) HalfHour, 
    SUM(case when s.appointmentType = 'Pair' then 1 else 0 end) Pair 
From Client as c 
left outer join [session] as s 
    on c.Entityid = s.ClientId 
where c.entityid =1 
group by c.firstname; 

SQL Fiddle with Demo

你沒有指定RDBMS,但如果您使用的是具有PIVOT功能(的Oracle 11g +時,SQL Server 2005+)的數據庫,然後將查詢會是什麼樣子的:

select firstname, Hour, HalfHour, Pair 
from 
(
    select c.firstname, s.appointmentType 
    from Client as c 
    left outer join [session] as s 
     on c.Entityid = s.ClientId 
    where c.entityid =1 
) src 
pivot 
(
    count(appointmentType) 
    for appointmentType in (Hour, HalfHour, Pair) 
) piv 

SQL Fiddle with Demo

兩個查詢的結果是:

| FIRSTNAME | HOUR | HALFHOUR | PAIR | 
-------------------------------------- 
|  Bob | 2 |  3 | 1 | 
+0

很不錯,我喜歡它。你之前有兩個版本,第二個版本和我的工作完全一樣,除了你的工作,我的工作除外。非常沮喪。不管,謝謝。 – Raif

+0

@Raif當我測試連接版本時,它不能正確工作。所以我刪除它以包含一個'PIVOT'版本。 – Taryn

0

你只能指望你的組被定義的,所以返回的計數是作爲單獨的行,並不是所有的在一排的最佳途徑。換句話說,這樣的:

bob | Hour | 2 
bob | halfhour | 3 
bob | Pair | 1 

,而不是這樣的:

bob | 2 | 3 | 1 

因此該查詢將如下所示:

SELECT 
    c.firstname, 
    c.Entityid, 
    count(c.clientid) as ct 
FROM Client as c 
GROUP BY c.firstname, c.Entityid 

一旦你讓他們爲各行,可以「透視「如果你真的需要的話,把這些表合併成一行。如果您有靈活性,您也可以在應用程序級別執行此操作。沿着這些線路的東西應該做的,沒有實際測試過,所以希望它很接近:

SELECT 
    t.firstname, 
    SUM(CASE(t.Entityid WHEN 'hour' THEN t.ct ELSE 0)) as hour, 
    SUM(CASE(t.Entityid WHEN 'halfhour' THEN t.ct ELSE 0)) as halfhour, 
    SUM(CASE(t.Entityid WHEN 'Pair' THEN t.ct ELSE 0)) as Pair 
FROM (
    SELECT 
     c.firstname, 
     c.Entityid, 
     count(c.clientid) as ct 
    FROM Client as c 
    GROUP BY c.firstname, c.Entityid 
) t 
GROUP BY t.firstname