重写查询以格式化sql结果的方式不同

时间:2013-01-24 14:55:19

标签: sql oracle oracle-sqldeveloper

我有以下查询来获取一周中每天可用的各种类型的产品数量。

select product_type, availDate, quantity 
from myTable 
where availDate between '2013-02-15' and '2013-02-21' 
order by product_type, availDate

这给出了以下结果......

product_type  |  availDate  |  quantity
--------------|-------------|----------
type1         |  2013-02-15 |  2
type1         |  2013-02-17 |  1
type1         |  2013-02-18 |  1
type1         |  2013-02-21 |  3
type2         |  2013-02-15 |  1
type2         |  2013-02-16 |  2
type2         |  2013-02-17 |  1
type2         |  2013-02-18 |  2
type2         |  2013-02-19 |  1
type2         |  2013-02-20 |  1

我实际上想要显示它是这样的:

product_type  | 2013-02-15 | 2013-02-16 | 2013-02-17 | 2013-02-18 | 2013-02-19 | 2013-02-20 | 2013-02-21
--------------|------------|------------|------------|------------|------------|------------|-----------
type1         | 2          | -          | 1          | 1          | -          | -          | 3
type2         | 1          | 2          | 1          | 2          | 1          | 1          | -

是否可以从查询中执行此操作,或者是否需要通过其他方式操作我的结果。??

由于

编辑:

现在有人告诉我这是Oracle SQL中的需要

2 个答案:

答案 0 :(得分:1)

您可以使用PIVOT查询,这个简单版本的缺点是您需要在查询中列出所有有趣的日期;

WITH cte AS (
  SELECT "product_type", "availDate", "quantity" 
  FROM myTable 
)
SELECT * FROM cte
PIVOT (SUM("quantity") AS Quantity for ("availDate") IN
       ('15-Feb-2013',
        '16-Feb-2013',
        '17-Feb-2013',
        '18-Feb-2013',
        '19-Feb-2013'))
ORDER BY "product_type"

SQLfiddle for testing

答案 1 :(得分:0)

如果有任何帮助,我确实发现了...... http://www.artfulsoftware.com/infotree/queries.php#78

可能有用。

亲切的问候, 西部高地白梗。