如何转换以下内容:
+------+---------+------+
| Date | Product | Sold |
+------+---------+------+
| 1/1 | P1 | 100 |
| 1/1 | P2 | 250 |
| 1/1 | P3 | 50 |
| 2/1 | P1 | 170 |
| 2/1 | P2 | 0 |
| 2/1 | P3 | 70 |
+------+---------+------+
进入这样一个表:
+------+-----+-----+----+
| Date | P1 | P2 | P3 |
+------+-----+-----+----+
| 1/1 | 100 | 250 | 50 |
| 2/1 | 170 | 0 | 70 |
+------+-----+-----+----+
使用SQL?
我知道产品的数量(正好是3个)。
答案 0 :(得分:5)
许多DBMS提供对“pivotots”或“交叉表报告”的特定支持,但如果您的DBMS没有,或者您更喜欢可以在各种DBMS上运行的解决方案,您可以写:
SELECT Date,
MIN(CASE WHEN Product = 'P1' THEN Sold END) AS "P1",
MIN(CASE WHEN Product = 'P2' THEN Sold END) AS "P2",
MIN(CASE WHEN Product = 'P3' THEN Sold END) AS "P3"
FROM ___insert_table_name_here___
GROUP
BY Date
;
编辑添加:您现在已经提到过您正在使用MySQL,不有特殊的数据透视或交叉表支持,所以上面的查询是要走的路。
答案 1 :(得分:0)
如果是SQL Server 2005 +:
SELECT
Date
, [P1]
, [P2]
, [P3]
FROM
(
SELECT
Date
, Product
, Sold
FROM
ProductSold
) AS t1
PIVOT
(
MIN(Sold)
FOR Product IN ([P1], [P2], [P3])
) AS pvt
ORDER BY
Date ASC;
答案 2 :(得分:0)
在MySQL中,如果要旋转的列数未知,则可以使用prepared statements,代码将如下所示(请参阅SQL Fiddle with Demo):
CREATE TABLE Table1
(`Date` datetime, `Product` varchar(7), `Sold` int)
;
INSERT INTO Table1
(`Date`, `Product`, `Sold`)
VALUES
('2001-01-01 00:00:00', 'P1', 100),
('2001-01-01 00:00:00', 'P2', 250),
('2001-01-01 00:00:00', 'P3', 50),
('2001-02-01 00:00:00', 'P1', 170),
('2001-02-01 00:00:00', 'P2', 0),
('2001-02-01 00:00:00', 'P3', 70)
;
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(case when Product = ''',
Product,
''' then sold else 0 end) AS ',
Product
)
) INTO @sql
FROM Table1;
SET @sql = CONCAT('SELECT Date, ', @sql, '
FROM table1
GROUP BY date');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;