以下是“销售”数据示例
这是所需的输出结果集
以下是将从此SQL语句生成的不受欢迎的结果集的示例。
SELECT Vendor, SUM(Markdown), SUM(Regular), SUM(Promotion), SUM(Returned)
FROM sales
GROUP BY Vendor, Date
有没有办法通过SQL获得所需的结果集?
我们正在IBM iSeries上运行SQL DB2数据库。
我确实意识到这是尝试这样做的一种非常奇怪的方式......我们只是想找到一种方法来根据需要恢复结果集,而不必通过代码手动转换结果。
答案 0 :(得分:6)
您需要使用UNION
声明
试,
SELECT Vendor, 'Markdown' as Type, SUM(Markdown) as Amount
FROM sales
GROUP BY Vendor, Date
UNION
SELECT Vendor, 'Regular' as Type, SUM(Regular) as Amount
FROM sales
GROUP BY Vendor, Date
UNION
SELECT Vendor, 'Promotion' as Type, SUM(Promotion) as Amount
FROM sales
GROUP BY Vendor, Date
UNION
SELECT Vendor, 'Returned' as Type, SUM(Returned) as Amount
FROM sales
GROUP BY Vendor, Date