PIVOT函数中必须要包含一个聚合函数,聚合函数分别是:COUNT、SUM、MAX、MIN、AVG,针对不同的使用场景,该选择哪个聚合函数,意义都是不一样的,下面还是举例说明吧!
我建了如下一张销售表并且插入一下测试值:
CREATE TABLE SalesOrder
(
门店 VARCHAR(50),
商品类型 VARCHAR(50),
销售额 INT
)
INSERT INTO SalesOrder
SELECT 'ShopA','A',round(100+100*rand(),0) UNION ALL
SELECT 'ShopA','A',round(100+100*rand(),0) UNION ALL
SELECT 'ShopA','B',round(200+100*rand(),0) UNION ALL
SELECT 'ShopA','B',round(200+100*rand(),0) UNION ALL
SELECT 'ShopA','B',round(200+100*rand(),0) UNION ALL
SELECT 'ShopA','C',round(1000+100*rand(),0)UNION ALL
SELECT 'ShopB','A',round(100+100*rand(),0) UNION ALL
SELECT 'ShopB','A',round(100+100*rand(),0) UNION ALL
SELECT 'ShopB','B',round(200+100*rand(),0) UNION ALL
SELECT 'ShopB','C',round(1000+100*rand(),0)UNION ALL
SELECT 'ShopB','C',round(1000+100*rand(),0)UNION ALL
SELECT 'ShopC','A',round(100+100*rand(),0) UNION ALL
SELECT 'ShopC','B',round(200+100*rand(),0) UNION ALL
SELECT 'ShopC','B',round(200+100*rand(),0) UNION ALL
SELECT 'ShopC','B',round(200+100*rand(),0) UNION ALL
SELECT 'ShopC','B',round(200+100*rand(),0) UNION ALL
SELECT 'ShopC','C',round(1000+100*rand(),0)UNION ALL
SELECT 'ShopC','C',round(1000+100*rand(),0)