我有多个表,每个表都有FK关系,可以将它们相互连接。我需要使用某些表中的详细信息创建数据透视表。
Region Table
Region_ID|Region_Description
State Table
State_ID|State_Description|Region_ID_FK
Order Table
Order_ID|Order_Date|State_ID_FK
Category Table
Category_ID|Category|Description|Order_ID_FK
我使用基于FK的自然连接加入所有表。
我需要确定每个地区每个类别的订单数量。
结果表应如下所示:
Category|Region1|Region2|Region3|Total
Sporting 1 0 3 4
ETC 0 2 1 3
答案 0 :(得分:0)
SELECT c.Category,
COUNT( CASE r.Region_ID WHEN 1 THEN 1 ELSE NULL END ) AS Region1,
COUNT( CASE r.Region_ID WHEN 2 THEN 1 ELSE NULL END ) AS Region2,
COUNT( CASE r.Region_ID WHEN 3 THEN 1 ELSE NULL END ) AS Region3,
COUNT( CASE r.Region_ID WHEN 4 THEN 1 ELSE NULL END ) AS Region4
FROM REGION r
INNER JOIN
STATE s
ON (r.Region_ID = s.Region_ID_FK)
INNER JOIN
ORDER o
ON (s.State_ID = o.State_ID_FK)
INNER JOIN
CATEGORY c
ON (o.Order_ID = c.Order_ID_FK)
GROUP BY c.Category