select City,noorder,upto2,more2 from (
select c.CustomerID,City, case 
when COUNT(orderid)=0 then 'noorder'
when COUNT(orderid)<=2 then 'upto2'
when COUNT(Orderid)>2 then 'more2'
end as category
 from customers c left join Orders o on c.CustomerID=o.CustomerID
group by c.CustomerID,c.City) d
pivot(count(customerid)
for category in(noorder,upto2,more2) ) as p
为什么 在City 前加上d就不行了。
select d.City,noorder,upto2,more2 from (
select c.CustomerID,City, case 
when COUNT(orderid)=0 then 'noorder'
when COUNT(orderid)<=2 then 'upto2'
when COUNT(Orderid)>2 then 'more2'
end as category
 from customers c left join Orders o on c.CustomerID=o.CustomerID
group by c.CustomerID,c.City) d
pivot(count(customerid)
for category in(noorder,upto2,more2) ) as p