mysql列反转Pivoting

Pivoting是一项可以把行旋转为列的技术。在执行Pivoting的过程中可能会使用到聚合。Pivoting技术应用非常广泛。下面讨论的都是静态的Pivoting查询,即用户需要提前知道旋转的属性和列的值。对于动态Pivoting,需要动态地构造字符串。

开放架构

开发架构是一种用于频繁更改架构的一种设计模式。利用关系型数据库和SQL语句可以非常有效地处理DML,包括INSERT、SELECT、UPDATE和DELETE。
然而,DDL在频繁进行架构更改时显得十分不方便。例如城对表结构进行修改,用户必须添加、修改或删除列,而这种操作正是关系型数据库不擅长的方面。
因此,在频繁更改架构的情况下,可以在一个表中存储所有的数据,每行存储一个属性的值,多用VARCHAR来存储,因为其容纳各种类型的数据。下面的语句生成一张开发架构的表t.
CREATE TABLE t(
id INT,
attribute VARCHAR(10),
value VARCHAR(20),
PRIMARY KEY(id,attribute)
);
INSERT INTO t SELECT 1,'attr1','BMW';
INSERT INTO t SELECT 1,'attr2','100';
INSERT INTO t SELECT 1,'attr3','2010-01-01';
INSERT INTO t SELECT 2,'attr2','200';
INSERT INTO t SELECT 2,'attr3','2010-03-04';
INSERT INTO t SELECT 2,'attr4','M';
INSERT INTO t SELECT 2,'attr5','55.60';
INSERT INTO t SELECT 3,'attr1','SUV';
INSERT INTO t SELECT 3,'attr2','10';
INSERT INTO t SELECT 3,'attr3','2011-11-11';
表的内容如下
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOcAAADFCAIAAAAg8nJKAAAO+ElEQVR4nO2d34skVxXH7/8kDEU9iIoRREE0+CAkD/YMpUR88MG3EAZFMD2zWILS5kEIQlBJemeGQGGIiWGCP/KQTbZntk1S+bGZbHY39sadnZ3p+dXj9aF+3fp1u6q7eu45dc6Hy9J753bXrW99+3b9OOde8Xz/RS5ccBXxfP9FyTCowOTag4MD010ABGU12LVYoawGJtc+ePDAdBcAQVkNdi1WKKvBrsUKZTUW6dr/XYz+9as7Lz/xYPh8vTf6rm27fq56f39/gRutTkn3LplKauSB0fk5WaBrP7/27L03fnz+8I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x8+1Y/X4qWEEPzMzIVQK6dCuX76nkoq8GuxQplNdi1WKGsBrsWK5TV4FwGBh881mKFshrsWqxQVoNdixXKarBrsUJZDXYtViirAcm1ZnMZMk90wT+s16mRWZdByvInumq+Q1nNZbavBDDXGsxlGMXTuAbxN5ijwodO1PlwDtDC6JlMvkNhjcqi21cHkmsVjOYytCEDJyJYMqQ8UjEfuKgPZVx0+2qAc63ZXIbI6AgCoyqpkcy6XBIVzq5tEGO5DEG7duSNJVOEz+jaWNIkY7nR9jMD1LXG1mXIfRpYprnWS606xmcIC8JsLkOy+FYLrsZGrp0+Ly/NZWDXzonZXIb0CQZ0y8oKvzzpa9OCO1+5fIeCmrKPXUT76gBy7VQo31fPQ1mN/wMPWrlSPoox/gAAAABJRU5ErkJggg==" alt="" />
从上面的例子中可以看到,在对通过开放架构设计的表进行添加、修改或删除表和列时,只需要通过INSERT、UPDATE、DELETE操作来完成逻辑架构的更改即可。当然使用这种方法可能导致数据库的其他特性无法使用,如完整性约束、SQL优化乖,同时查询数据变得不如之前的SQL语句来得直接和直观。所以,对于利用开放架构设计的表,一般使用Pivoting技术来查询数据。
Privoting技术需要和聚合一起使用,首先要确定结果的行数与表中行数的关系。对于开放架构表t,应该有3行5列,这可以通过分组id来得到。因此可以通过下列Pivoting进行行列互转以得到数据。
SELECT id,
MAX(CASE WHEN attribute='attr1' THEN value END) AS attr1,
MAX(CASE WHEN attribute='attr2' THEN value END) AS attr2,
MAX(CASE WHEN attribute='attr3' THEN value END) AS attr3,
MAX(CASE WHEN attribute='attr4' THEN value END) AS attr4,
MAX(CASE WHEN attribute='attr5' THEN value END) AS attr5
FROM t
GROUP BY id;

Pivoting先根据id进行分组,确定行列互转后记录的行数。之后通过已知的5个属性来确定行列互转后有5列数据,并通过CASE得到每列的值。由于使用了分组技术,因此一定要使用分组函数来取得列的值,故这里使用MAX函数,当然也可以使用MIN函数。最后得到的结果如下图

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAYoAAABUC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Ix0IoWyZBEFhotyeLNGNyFORCkIcHz5VP03bbMRgTIkP2ZAzkQpCHB49Xo9p2DMaEyJA9GQO5EOThwePVqLYdgzEhMmRPxkAuBHl48Hg1qm3HYEyIDNmTMZALQR4ePKtGtVMP3HkjRAbInqLypZao7SzpopbFsfX1VKmyJc8ZGBrjXz/VpHnW6GdVeKKErhrI9s9HPaodS9PqjRAZ6GyZ7enoOpDeoZ8mHW/PC5Zk9d0otT2tlWoSOrxnZctsrRHpu/2GKEe1a2lavREiA724ixivjUWlPcl/ujuSe1R5yxZRI8MWHKtnT7rZSHpBb3Gnny2zu0b9rdn2G6Aa1c6lafVGiAycPcUhZw1v4sphk+UDqyYXXUNlEdVykljhmfbUf5avDC17WiNbZneN+lsX7Mm9NK3eCJGxMHvSX9zlZIk4Ohd3XMivCHQdpxX37WmtbJktNUL2y7SP9mZZa1RjT9PqjRAZaHtKIl4bi3qLDiHxc1knpUYL40UcglzE6cLxxd262TK7a9Tfujl74sjTtHojRAYoHV15fq01ewrryzopy6J0UXkRdSQ5g2Mde0J2afxZ2TI7a9TfumBP7qVp9UaIDNCduzJVZnMZoxg2QjJ84d5ce258oCWSAq07d7qpJkHDe262zJaars320X5DtG94uZCm1RshMvRYpjGQC0EeHjxajwsZHH52n3tyRYgM2ZMxkAtBHh48Xj1s7Y0QGbInYyAXgjw8eLx6Vc12DMaEyJA9GQO5EOThwePVqLYdgzEhMpQtkyAILLTbE0EQBDbIngiCQArZE0EQSCF7IggCKWRPBEEgheyJIAikkD0RBIEUsieCIJBC9kQQBFL+D42mrzc2iozFAAAAAElFTkSuQmCC" alt="" />

这种旋转方式是非常高效的,因为它只对表进行一次扫描。另外,这是一种静态的Pivoting,用户必须事件知道一共有多少个属性,然而对于一般开放架构表,用户都会定义一个最大的属性个数,这样可以比较容易进行Pivoting
 

关系除法

关系除法(Rational Divistion)和常见的关系运算JOIN、SEMI JOIN一样,都是一个关系代数。
当除数集合中的元素数量较小时,Pivoting可用于解决关系除法问题。先通过创建表t并填充数据。
CREATE TABLE t1 (
orderid VARCHAR(10) NOT NULL,
productid INT NOT NULL,
PRIMARY KEY(orderid,productid)
);
INSERT INTO t1 SELECT 'A',1;
INSERT INTO t1 SELECT 'A',2;
INSERT INTO t1 SELECT 'A',3;
INSERT INTO t1 SELECT 'A',4;
INSERT INTO t1 SELECT 'B',2;
INSERT INTO t1 SELECT 'B',3;
INSERT INTO t1 SELECT 'B',4;
INSERT INTO t1 SELECT 'C',3;
INSERT INTO t1 SELECT 'C',4;
INSERT INTO t1 SELECT 'D',
表的内容如下
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAADNCAIAAACegs1sAAAKMUlEQVR4nO2d3Wsc1xmHz98UgRj2orSlKZQWSht64ZBcZCW2JaUXveidk4iWQr2S6RZaXF8YTMG0RdUXAdEQx40T+hFo5Gglq3HWsi3FkZ3KsUeytKuPVX+9mNnR7Ox5VzOZs17tOb+HF7MfZ9cz7z56Z7Tz6hw1OfUmg6ENNTn1JgjR4a4c29vb/d6E00g8LZSDtEE5AGBra6vfm3AaiaeFcpA2KAdAOQRyyPG/o81//frB269urUzm3YpapVCo1J7Nq3T4vm/ibWIYTE53jCRBeJN4WrLJ8cXC5Ucf/OTw6QcPr73i3363Fxt3whhzcjx58sTE2xxjMjndSZ+EaGTqTMbTEspxeNhs7B10j83FP/733ZcO/T/4y68/+ufZO1d+cO8f0ye+Soyb5z3v/PKzeVVHNJtHDx5+nmavU4bh5JhKQpeRuqeCtNQb+0GEchwcNqOHpLj/9s/2H/9pb+Ps3sOL/uLZ+vrrn1z6lmbk8oSnAkZng7veRHkkdle18CaW2h7xysvt45cnvOSY1qvyRbN59NnGgzR7nTLSJieeJW+02Nqr4myXRI3OJhOrlDexFCWnleSlxn69MVdU0XuulKPMjoymyWSQli8jx8O/V3ZWf1W/96PG+k/rd1+uf/LCjV98tXNYMdjVxv7SuKdG5oKtCR4JNj28He7PXDG+88E+a8YkHjl1cqRMTpscwQ9DY78+Oxr+JO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6JDvBrMX8urK2lA1QDq4O2QXX5RCgHADlEKAcAOUQoBwA5RDQyNHr5iIyQCTlcBCflUMH5QAohwDlACiHAOUAKIcA5QAoh0BWOeZLNl61d1QOk3OChWbY0+MT4a4cpuYEs+xKbBxH5YiRd04wy/pG47gsh5k5wSiHxeSdE4yHFYvJPScYT0jtwuicYAB/lbUJzgmWCjflOBHKAVAOAcoBUA4BygFQDgGNHL1uLiIDRFIOB/FZOXRQDoByCFAOgHIIUA6AcghQDoByCGSVg1+fW4iJOcF44c1KjMwJxkv2FmJqTjA2+9iHsTnBKIdlmJwTjIcVyzA6JxhPSG3F0LRP/FXWRjgnWBdcl0OAcgCUQ4ByAJRDgHIAlENAI0evm4vIAJGUw0F8Vg4dlAOgHAKUA6AcApQDoBwClAOgHAJZ5OCSGpZieHXIcKWmsc6/zB5InJbD9OqQgF1X8N2Vw/DqkNGVWIvWAHRWjt6sDtl5d5BxU46erQ7Jw8rg06vVIbl0qFVwdcguUA52gom4LocA5QAohwDlACiHAOUAKIeARo5eNxeRASIpByGdUA4iQjmICOUgIv8HG8yGQIz82IgAAAAASUVORK5CYII=" alt="" />
表t存储订单中包含的产品,比如A订单中包含的产品的ID为1、2、3、4,B订单中所包含的产品为2、3、4,以此类推。这是一个比较典型的关系除法问题。用Pivoting技术可以反订单中的产品旋转到单独的列中。例如要查询包含productid为2、3、4的订单,可以采用如下方法:
SELECT orderid
FROM (
SELECT
orderid,
MAX(CASE WHEN productid=2 THEN 1 END) AS p2,
MAX(CASE WHEN productid=3 THEN 1 END) AS P3,
MAX(CASE WHEN productid=4 THEN 1 END) AS p4
FROM t1
GROUP BY orderid
) AS P
WHERE p2=1 AND p3=1 AND p4=1;

上述语句返回“A”和“B”。如果单独运行子查询,将会得到每个订单对应的产品ID,得到的结果如下

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQ8AAABhCAIAAABHxLP3AAAIiElEQVR4nO2d22/bVBzHz5/Td6TI5AEBYqgIJAQTD0jbw5Iq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NHVbWGaZuTZDdQm7upG4VOpPAqnjvlmJaOxX0qZdHltIjxmmhG7ewcn6kkO4PvFtozp0kNu7YjOduqZ4HtKLvX9IvybpyC1+Pze+dpgLrFs4pjkEmNhffjNdu2Stro+gXjxXS/d26hVddB7cIzw63iHNLjSU6dovVSrhFTHZciQl0C+Prsfl0DOcWzjlFt+BTfudR97lFX19MpwqpEXW9+h2A4SL92zN8bgmyWzi+Qe40zN+JmYre7KJUIaVF45rU0mLdQ8apfSeGuZNBQdz9Fi/OVwF3iwNBvztJE9zL9ydwix/BODF/Arf4EbjFnwTALd3NNgOADs3d0oOoxM4tsvvgpha5VWEP3EIhqGmRWxX2wC0UgpoWuVVhD9xCIahpkVsV9sAtnobA+y2UtMitCnt6+7+Ge1xhQudOUtIiBG9/d1L//ZbBGI2BYt5XmNi5k5S0eIyA353knNYAfs8rTPDcSUpaBOD5b4M1PgwyXleY6LmTlLQIAG5pC/EV5u3cSUpaBCDALbgS66rCPJ07SUmLAPArrW0h+lpfX+/Z3ElKWgSA351sC7HfI3k/d5KSFo/B3Mm2EXePwsVtSr/fIkaL3KqwB27xNHAvvyMtcqvCHriFQlDTIrcq7IFbKAQ1LXKrwh7MnQSghuZuAQA0BW4BoFXgFgBaBW4BoFX+B5ohsC8IpFR5AAAAAElFTkSuQmCC" alt="" />

对于这个问题,聚合函数可以使用COUNT来替换MAX,这会让派生表的结果显得更加直观。此时若产品存在则返回1,不存在则返回0而不是NULL,故SQL语句可调整为
SELECT orderid
FROM (
SELECT
orderid,
COUNT(CASE WHEN productid=2 THEN 1 END) AS p2,
COUNT(CASE WHEN productid=3 THEN 1 END) AS P3,
COUNT(CASE WHEN productid=4 THEN 1 END) AS p4
FROM t1
GROUP BY orderid
) AS P
WHERE p2=1 AND p3=1 AND p4=1;

格式化聚合函数

Privoting技术还可以用来 格式化聚合数据,一般用于报表的展现。为了演示用Pivoting技术来格式化,下面给出一个例子。先通过创建表t2并填充数据
CREATE TABLE t2 (
orderid INT NOT NULL,
orderdate DATE NOT NULL,
empid INT NOT NULL,
custid VARCHAR(10) NOT NULL,
qty INT NOT NULL,
PRIMARY KEY (orderid,orderdate)
);
INSERT INTO t2 SELECT 1,'2010-01-02','3','A',10;
INSERT INTO t2 SELECT 2,'2010-04-02','2','B',20;
INSERT INTO t2 SELECT 3,'2010-05-02','1','A',30;
INSERT INTO t2 SELECT 4,'2010-07-02','3','D',40;
INSERT INTO t2 SELECT 5,'2011-01-02','4','A',20;
INSERT INTO t2 SELECT 6,'2011-01-02','3','B',30;
INSERT INTO t2 SELECT 7,'2011-01-02','1','C',40;
INSERT INTO t2 SELECT 8,'2009-01-02','2','A',10;
INSERT INTO t2 SELECT 9,'2009-01-02','3','B',20;
表的内容如下
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAV4AAAC+CAIAAADyevB7AAAV/klEQVR4nO2d3Y/dxnnG+TdJwOKAF0VbNAWKFijaoBdbJBc6EtgiRS560TsrEFoU6K5klAVabH0hIChgtIWz0goBiAZxtvEG/QjQ2NHuehuHVmwrjux0nXgl7bdWnVwMyRmSw+HMHH68s3x+IIQjLsnz8hnyOUPyzHOCN9a/iQkTJkyVKXhj/ZsMAADKTNcanj17NnYJPuGLXKjTjXo9sAZghC9yoU43YA2Cp0+fjl2CT/giF+p0o14PrAEY4YtcqNMNWIOAWtsQxxe5UKcbw1rD/7/c/++//eTbX3m690Y3G0zjMIzTjtY6ODhoX3f0XXDb5R4wkmtIFmnWHt7XFmp61uvp0Rp+8fbXP/v+V188//6nm9cO3v9uB1s0aZX6Mg1rff75561vOM4uGC4/rGuYyNUjnTarxdsZv68tQ+hpU2q9nswaXry4ODk973Daf/jP//fdL704+KeD3a999l+v/OT1P/rwP+8tutl3X53NXt3tYq2Li5effPpz/V6T2AXN8m5qOE0mcg09uTYrBdkH0tO4VF7P8cmZPGXWcP7iovKHBaePv/0XZ7/8l9Mnr5x++trBw1eOH3/tx3d/p3H53TuzgHNjg/93dmf1uvTfIGd2Z6c0Z7a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vDqzLkQdlIeVocQtYgYZI7UCDsYC/qXiBLhtSTGygGZWcsNChb2gpSnjjUrIH3BE06xgXSBcUksiEzciNAlItADoBzsQakPFnJNQZWsbHTuqDIKSSCNSjgFxd20cNIeSpD0xqK6+cCI2tgSaQL0hiCYfSUrRMXFDVU6W8MKU+W0LGGNC4d7i69hrEjnthQTyjK2TW4DZmjecTFkPJkCR1ryLze/pm0dK9h5C4D619PZRYWHl4aQehY9wFf5EKdbsAaBNTahji+yIU63YA1CKi1DXF8kQt1ugFrEFBrG+L4IhfqdKPRGqzSYAAAlw+1NQAAgAysAQCgANYAAFAAawAAKIA1AAAUwBoAAApgDQAABb8CjV4mg+ALNNkAAAAASUVORK5CYII=" alt="" />
可以将表t2看作一张汇总表,比如网上商城的购物明细。这份汇总表显示了订单号、订单日期、员工编号、消费者编号和订单数量。要在此汇总表的基础上进一步统计每个月消费者每年的数量,可能会想到分组来得到结果,例如
SELECT custid,YEAR(orderdate) AS year,SUM(qty) AS sum_qty
FROM t2 GROUP BY custid,YEAR(orderdate)
运行结果如下
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAL8AAACpCAIAAAD1B3vXAAAKSklEQVR4nO2dS27jSBKG81QCwRP4GiUbXOgUtRzTaoA7n8HosS2jAR2gNl4OLKm9ITDd1e7pnkEtSuWyJD9kxCz4SolUlEglgwxmfMgFlaZUfzB/PoT8S6l+vvxFmrRqTf18+QsIQiU4uefx8bFpCaXhqBlhqxxxT71w1IzA2D3fvn1rWkJpOGpG2CpH3FMvHDUjiHtI4agZoQn3hIHrBuHBHzOfzw2IoYWjZoStcsy5J7VI3iuG3PP169eDP4MaBprLjM5WObF73t7Wq+fXg9qvPznOT7Oyf9q7rdfvf//3fwZ0EjYemvcenaic5eolbbF7Xt/Weu9y9bJc3fRVTP9s6DjDadQ/i7enZ078Z2c4Xd376avjk3jn2TDpi/Z5yf0TJdp6/f6fv/4u0mmw3fuO6o/S8h1/plfh+LOXpV54uoMz9I+VUiejejRv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haNmBHEPKRw1I5Rzj2QLO74msmQLjWHhmsiSLawDe9ZETpFsoSGsWRM5Q7KFprBnTeQUyRaawcI1kSVbaAIL10SWbKEpLFwTWbKFrYajZgRxDykcNSOIe0jhqBlB3EMKR80Ixe4xnD8TukuBe1gwZ3gec9SMIO4hhaNmBHEPKRw1I4h7SOGoGUHcQwpHzQjl3CPZwo6viazNS6SzWpItrITdayJH6TDJFhrAwjWRo2yGZAsPxrI1kS/c7D4l2cJDsXBNZEgyYpItPAgL10SOiJ54JFtYFfvWRH4INjKppp+aJVvY6TWRYZwFC/X/2CXZwlbAUTOCuIcUjpoRxD2kcNSMIO4hhaNmhGL3GM6fCd2lwD0smDM8jzlqRhD3kMJRM4K4hxSOmhHEPaRw1Iwg7iGFo2aE8u6599J4YbMRn9pHwspsYcStB0fJnKixmYrwk6vPcI0vm5ztqn0kLMwWAgDArQcDL55RNzlLGpw3HwpLoRwJe7KFDwEMgqJfnjORLWx+aj2FbiSsyRbG1oG6f7ewBZCNhD3ZwiiTmjUXBgbd47UgzpxCMxKWZgvruHPZ9dRsX7YwI6zhqRliA1nxjd3GbGGKdqWRbGFb4KgZQdxDCkfNCOIeUjhqRhD3kMJRM0Kxewznz4TuUuAeFswZnsccNSOIe0jhqBlB3EMKR80I4h5SOGpGEPeQwlEzQjn3yO8WdnxN5IRasoUbv/7UtIFqHwkL10QGgPqyhRv5nqZ/PoxyJOxZE7nObOH5ZmCh0agh3UhYsyYyZbbQFvfYsyZyvdlCC+9cFq6JDFD7nWvsdf6p2cI1kVPqyBZa9XvNFq6JnCHZwhbCUTOCuIcUjpoRxD2kcNSMIO4hhaNmhGL3GM6fCd2lwD2CUAFxj1AdcY9QHXGPUJ3/A2ZwkOsuYQrLAAAAAElFTkSuQmCC" alt="" />
上述结果没有任何问题,只是显示的可能不够直观。如果可以通过旋转得到输出结果,那就直观和清晰多了。
这里同样可以使用Pivoting技术。与之前唯一的不同是,此处不再使用聚合函数MAX,而是使用SUM函数。这个解决方案的SQL语句如下:
SELECT custid,
IFNULL(SUM(CASE WHEN orderyear=2009 THEN qty END),0) AS '2009',
IFNULL(SUM(CASE WHEN orderyear=2010 THEN qty END),0) AS '2010',
IFNULL(SUM(CASE WHEN orderyear=2011 THEN qty END),0) AS '2011'
FROM
(SELECT custid,YEAR(orderdate) AS orderyear,qty FROM t2) AS p
GROUP BY custid;
上述SQL语句中的IFNULL函数用来将NULL值返回为0,代表该年消费者没有产生任何订单操作。
使用Pivoting技术来格式化聚合数据会遇到一个问题,即当旋转的元素非常多时,会产生较长的查询字符串。要缩短查询的字符长度,可以预先产生一张矩阵表,包含每个要旋转列的属性,运行如下语句创建并填充矩阵表Matrix
CREATE TABLE Matrix (
orderyear INT PRIMARY KEY,
y2009 INT NULL,
y2010 INT NULL,
y2011 INT NULL
);
INSERT INTO Matrix SELECT 2009,1,0,0;
INSERT INTO Matrix SELECT 2010,0,1,0;
INSERT INTO Matrix SELECT 2011,0,0,1;
矩阵表Matrix的内容如下
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAARMAAABQCAIAAAC1cAaZAAAIr0lEQVR4nO2d32sjVRTH79+0hTD2QVRUEAVR8aGiD52UKIoPPvi2q6AINs1iBEX7UCjCotLdNlEoimt1EX+BVptkq2u23W1du7vur7RNJmmaen2YOzfzezLJzOacyflwKDNnbm6/c898cydDLmELZz6noKAIG2zhzOecIIiQkHOC2dvbG7aEEJDa+DCrJecEg7e68MGrlpwTzO7u7rAlhIDUxodZLTknGLzVhQ9eteScYPBWFz541cbpnP+Obvz0ztWvXtxdX4imw2p+fDxfjaavENRqtbv+P/uH1MaHWW2Mzrm1On/z55cP93++tjJZu/htBD0OyTl37tyJpd9qfpwJjNNazohEZlk06iUDR62hsFsmXGq9Mi5qhXMODzvNVjvCuLH28b/fPntY+6hWee3mj8c3Tz19+YfFQbs9f1JRTlYi1RkYnc7R1WvXIx+fZqvdLE6li/r2Z2l2z8z5diHN9Ewldw9Lf9ZsOTPrM4rINItTzDEaw1Ur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+6uFYZ4FIr6OGb3clyTl9rQv2SnHN41cW1sg2XWsFoOaffNaF+Sc45vOriuhZxqRWMkHMGWBPql+Scw6survsfXGoFo+KcAdeE+iQ55/Cqi+szNy61gpFzTr9rQt0XihoArC6u57y41Pa4gjURzokZgNX1gdTGBzknHHirCx+8ask5weCtLnzwqiXnBIO3uvDBq5bWhBJECOzOIQgiFOQcgugHcg5B9AM5hyD6gZxDEP3wP3A/h0SroP4EAAAAAElFTkSuQmCC" alt="" />
因此可以通过将表t和表maxtrix进行连接把原来的:
SUM(CASE WHEN orderyear=n THEN qty END) AS N
替换为SUM(qty*yN) AS N
完整的SQL查询语句为:
SELECT custid,
SUM(qty*y2009) AS '2009',
SUM(qty*y2010) AS '2010',
SUM(qty*y2011) AS '2011'
FROM
(SELECT custid,YEAR(orderdate) AS orderyear,qty FROM t2) AS O
INNER JOIN Matrix AS P
ON O.orderyear=P.orderyear
GROUP BY custid;
运行结果如下
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAANoAAABhCAIAAAA/cig6AAAHOklEQVR4nO2dz27aShSH56mQ6yfIa9REXvAU3WKoxC7PEFWhpJV4gGyyLhA2lm6bpre9V1mUpPwLcTR34bE9YDvgY8/M8eV8moWZOOTz+GcmmJMJ+3DxmRo1JI19uPjMCQIHdYrj4+OjaYVcyA3GjhvFsRrIDUaN4/jw8GBaIRdyg7HjRnGsBnKDQXFUArnBMBFHv2fbPb/008xmswpk1EBuMHbcqotjnLl0+CqK4+/fv0s/B+d+z2aCSGroig53KHY6pMeUW+STDClmt7yebDcRx+fnYLXelGo37y3r/aTolw5uQfDy659/K/C8PG1ehtufmuxN52YzaLKwZ9J9w5qfVut0z7RjiZ7V5SlLHYtON7HNWKyRuQ8St8yeHbfl6iluIo6b50DuXa6elqtLJ7oanE7XsrrjsH8itscdS3zZ6o5XUy9+1DwVO0+6UV+4z1PqRxRoQfDy989fWZ7gNvUsy5tcOux0sHVor/Zsbet3i3ZIHubvY94tv0dyOyiOnsW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GcawGcoNBcVQCucGgOCqB3GBQHJVAbjCKxdGW6ieSD68NoXVYy1U1H6+bZBJ/Ql3Zh4TJZ9ZJpZkxtA5ruapmcuNR+a2aEoqpyy4y1+XXh6lJB1DVrA3MbqFVlQVm0mR9dH8rI/jfVVxrICwQvk75lC2/Pd7JOgJW1awHzG480lMTRz5032X/Fx1t6B9WcFWzBjC7hYS/NVY6Wcu/Ox7Vq2O5quajdbvrbV0kVb+VSX53NPzSyGtV1Xy0bny4W0JfyI1ug1cDucGgOCqB3GBQHJVAbjAojkogNxjZcSxXz0sQcDLiWAtm9bnKUVEjN4pjNZAbDIqjEsgNBsVRCeQGg+KoBHKDUTyOUzdZU89oyaPxYcXyQVwW2Nxg65Yfsr5j8mn18MLkJ9dmTzmeMoU02NzA65bvXd/RfNVtjNlTjrOIKwSVW5l1y/dW9Jgv5InBcsoxlbiG4HEruW55oeVGDUOnPA88biXXLd8TR+PL08tgOeUIJsQdMLqpmKzprUwMtrcLMhjdQOuWH/RvjuhGTwi2myky6NxA65bTbfBqIDcYFEclkBsMiqMSyA0GxVEJ5AYjO47l6nkJAk5GHGvBrD5XOSpq5EZxrAZyg0FxVAK5waA4KoHcYFAclUBuMIrF8XjXBs8C2wdxsIpr/ahZG9x0Is0OK7YyBXDFtWaU/Xt10wvgmh1WVEVcZSquNaNmuVHOjS+Ai2VYTZe4lqy41oy6anCKY8Z2iE63khXXmlEWR5qswy08E+IRT9ZDl97KYHu7AKq41oyitcHN/9FMjW5YaAJUca0fqgbXDbnBoDgqgdxgUByVQG4wKI5KIDcY2XEsV89LEHAy4kgQGKA4EoigOBKIoDgSiPgP/6C1SmSxBIYAAAAASUVORK5CYII=" alt="" />
Unpivoting
可以将Unpivoting看做Pivoting的反向操作,即将列旋转为行。要完成这个示例,需要根据下列语句创建并填充表p,
CREATE TABLE p (
custid VARCHAR(10) NOT NULL,
y2009 INT NULL,
y2010 INT NULL,
y2011 INT NULL,
PRIMARY KEY (custid)
);
INSERT INTO p
SELECT
custid,
IFNULL(SUM(CASE WHEN orderyear=2009 THEN qty END), 0) AS '2009',
IFNULL(SUM(CASE WHEN orderyear=2010 THEN qty END), 0) AS '2010',
IFNULL(SUM(CASE WHEN orderyear=2011 THEN qty END), 0) AS '2011'
FROM
(SELECT custid, YEAR(orderdate) AS orderyear, qty
FROM t2 ) AS P
GROUP BY custid;

这里把t2表返回后的内容导入到表p中,如果想得到t2表直接聚合得到的结果,这个问题就变成了Unpivoting问题。解决这个问题需要将列旋转为行。这里使用的技巧是对每行数据产生3个副本,每个副本产生一个需要旋转的列,这个过程可以通过如下的CROSS JOIN来完成。

SELECT * FROM
p,
(SELECT 2009 AS orderyear
UNION ALL SELECT 2010
UNION ALL SELECT 2011) AS o
得到以下结果
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUwAAADyCAIAAACpu2u5AAATGUlEQVR4nO2d3Y/cVhnG/T8hraZzgQBRJAQSgooLpPYis9GAirjggruqWoGQ2I+KQQKFXiBVSBWgNpvdVhpRlZaqFR+96Ed2N0vb6UeapklKApmk+5XdCYcLezwe+9hjv+t3fB77+ckXOyfeze/YfiZej/3Ee+b881y4cKnx4j1z/nlDCKkvTQn53bt3q1YoAG31wLKVEZsjQ+4itNUDy1ZGQ0N+586dqhUKQFs9sGxlxObIkLsIbfXAspXBkANAWz2wbGWcLuT/u3/zn7+8/uKjd3afKdnLyqDXbvcGZfyk4XBYxo+ZE7TVY6625R3AhYjNsVjI//PmU7de/9HJ56/fePnM8P1XyjEKN0Ryi5S3jW7fvl3Gj0kw6LW9gLFpvxsMdPvBSnlG3LEdG062PJZt2oiyrZWKQh6bYxDyk5PR4dFx9nLz4h/+/crDJ8PfD3cev/WPxz58+ruX/74+87tmL5eeaLWe2Cn6R0WW0ej+9Ruf5Zlj4WXz7OKm//Vzi94Dq5eONxY9f2Rn7QFv8bnDo+TI7morGDncPOslJlitbfC154Vi1nWctbWOzMPWupR0ABda/DkeHN4LlyDkxyej6Kh1ufriT+79949H1x47uv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XGIzTBzIEczzGRNxQtv/AhNAYCPedgMo0/OZpjoan68y/sIrS64tmuzoa0eWLYyGHIAaKsHlq0MhhwA2uqBZSuDIQeAtnpg2cqwh7xQ6QQhxHEsIa89Q6j3b9rqgWUrgyEHgLZ6YNnKYMgBoK0eWLYyGHIAaKsHlq0MhhwA2uqBZSujYMh5W6sa7t96yWaYeSBthkkbMWyGcQT3H6JgM8ycEDXDWEdCThFyPmpaHo4/DslmmErI3wyTOmKMYWmEI7hcbMBmmGoo0gyTOmKMYcgdweUDkc0wlVCoGSZ1xBjD03VHwDil5On6vCjaDJM6YoxhM4wjYFwcYjPMHBA1w6SOGGP4EZo7AHzMw2YYfcTNMMmREN4MAwBt9cCylcGQA0BbPbBsZTDkANBWDyxbGQw5ALTVA8tWhj3khUonCCGOYwk5IaSuMOSE1ByGnJCaw5ATUnMYckJqzv8BxAGs6/DO2YsAAAAASUVORK5CYII=" alt="" />
接着问题就简单了,只需根据orderyear列来取得对应旋转列的值,例如:
CASE orderyear
WHEN 2009 THEN y2009
WHEN 2010 THEN y2010
WHEN 2011 THEN y2011
END AS qty
因此这个Unpivoting问题的解决方案如下
SELECT custid,orderyear,
CASE orderyear
WHEN 2009 THEN y2009
WHEN 2010 THEN y2010
WHEN 2011 THEN y2011
END AS qty
FROM
p,
(SELECT 2009 AS orderyear
UNION ALL SELECT 2010
UNION ALL SELECT 2011) AS o
若要得到最终结果,则还需要过滤qty等于0的情况,因此最终的解决方案为:
SELECT custid,orderyear,qty
FROM (
SELECT custid,orderyear,
CASE orderyear
WHEN 2009 THEN y2009
WHEN 2010 THEN y2010
WHEN 2011 THEN y2011
END AS qty
FROM
p,
(SELECT 2009 AS orderyear
UNION ALL SELECT 2010
UNION ALL SELECT 2011) AS o
) AS M
WHERE qty <> 0
上一篇:[BZOJ 3745] [COCI 2015] Norma


下一篇:Mongodb的windows服务安装和卸载