2012-08-30 56 views
1

我有兩個表CustomersCustomerStatusEntriesSQL組利用兩個場

CustomerStatusEntries 
--------------------------- 
Id | Branch | CustomerStatus_Value | Customer_Id 

CustomerStatus_Value = ("B" = "Block" , "E" = "Created" etc...) 

我需要得到這個輸出

enter image description here

+3

至極RDBMS?請發佈表結構和樣本數據,它會幫助很多人獲得一些答案,而不是-1的批次 – Yaroslav

+1

您需要'PIVOT'。如果你透露你正在使用什麼樣的SQL,有人可能會告訴你如何。或者你可以搜索。 – podiluska

+0

上午使用SQL Server我說的領域,用戶需要幫助我...我認爲可以輕鬆得出結論,客戶表有一個ID,這是主鍵... – rtp

回答

3
SELECT Branch AS 'Branch Code', 
    SUM(CASE WHEN CustomerStatus_Value = 'E' THEN 1 ELSE 0 END) AS 'Created', 
    SUM(CASE WHEN CustomerStatus_Value = 'A' THEN 1 ELSE 0 END) AS 'Active', 
    SUM(CASE WHEN CustomerStatus_Value = 'B' THEN 1 ELSE 0 END) AS 'Blocked', 
    SUM(CASE WHEN CustomerStatus_Value = 'C' THEN 1 ELSE 0 END) AS 'Cancelled', 
    COUNT(CustomerStatus_Value) AS 'All' 
FROM CustomerStatusEntries 
GROUP BY Id 
+0

把他們在正確的順序:) –

+0

+1,但仍然缺少「總計」行,也似乎「Id」不存在,「Branch」別名爲「分支代碼」。 –

+0

全部工作! – rtp

1

假設列的固定數量的你已經顯示在您的示例中,您可以這樣做:

SELECT Branch, 
     SUM(CASE WHEN CustomerStatus_Value = 'E' THEN 1 ELSE 0 END) AS Created, 
     SUM(CASE WHEN CustomerStatus_Value = 'A' THEN 1 ELSE 0 END) AS Active, 
     SUM(CASE WHEN CustomerStatus_Value = 'B' THEN 1 ELSE 0 END) AS Blocked, 
     SUM(CASE WHEN CustomerStatus_Value = 'C' THEN 1 ELSE 0 END) AS Cancelled, 
     COUNT(*) AS All 
    FROM CustomerStatusEntries 
    GROUP BY Branch; 
1

你可以使用標準的SQL做到這一點:

select branch_code, 
     sum(case when CustomerStatus_Value = 'E' then 1 else 0 end) as Created, 
     sum(case when CustomerStatus_Value = 'B' then 1 else 0 end) as Blocked, 
     ... 
from t 
group by branch_code 
order by 1