私は2つのテーブルを持っていCustomers
ますCustomerStatusEntries
:
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