重新格式化结果的SQL查询

时间:2013-01-30 22:41:11

标签: sql select db2

以下是“销售”数据示例 enter image description here

这是所需的输出结果集 enter image description here


以下是将从此SQL语句生成的不受欢迎的结果集的示例。

SELECT Vendor, SUM(Markdown), SUM(Regular), SUM(Promotion), SUM(Returned)
FROM sales
GROUP BY Vendor, Date

enter image description here


有没有办法通过SQL获得所需的结果集?

我们正在IBM iSeries上运行SQL DB2数据库。

我确实意识到这是尝试这样做的一种非常奇怪的方式......我们只是想找到一种方法来根据需要恢复结果集,而不必通过代码手动转换结果。

1 个答案:

答案 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