我有两张桌子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