我有兩個表Customers
和CustomerStatusEntries
:SQL組利用兩個場
CustomerStatusEntries
---------------------------
Id | Branch | CustomerStatus_Value | Customer_Id
CustomerStatus_Value = ("B" = "Block" , "E" = "Created" etc...)
我需要得到這個輸出
我有兩個表Customers
和CustomerStatusEntries
:SQL組利用兩個場
CustomerStatusEntries
---------------------------
Id | Branch | CustomerStatus_Value | Customer_Id
CustomerStatus_Value = ("B" = "Block" , "E" = "Created" etc...)
我需要得到這個輸出
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
假設列的固定數量的你已經顯示在您的示例中,您可以這樣做:
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;
你可以使用標準的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
至極RDBMS?請發佈表結構和樣本數據,它會幫助很多人獲得一些答案,而不是-1的批次 – Yaroslav
您需要'PIVOT'。如果你透露你正在使用什麼樣的SQL,有人可能會告訴你如何。或者你可以搜索。 – podiluska
上午使用SQL Server我說的領域,用戶需要幫助我...我認爲可以輕鬆得出結論,客戶表有一個ID,這是主鍵... – rtp