将行作为sqlite中的数据透视表中的列

时间:2014-03-20 22:39:35

标签: sql sqlite

我有这个sql select语句:

Select ORDERS.ptDate as Date,Products.Description as Product, 
            ORDERDETAILS2.Quantity   FROM         ORDERS inner join ORDERDetails2 on Orders._id=ORDERDetails2.PtOrder inner join Products on Orderdetails2.ptproduct=Products.PtUnique order by date

对这种数据进行了反复推理:

2014-03-19 00:00:00;"Product a";"4"
2014-03-19 00:00:00;"Product c";"750"
2014-03-19 00:00:00;"Product a";"1"
2014-03-19 00:00:00;"Product b";"1"
2014-03-19 00:00:00;"Product c";"1075"
2014-03-20 00:00:00;"Product b";"2"
2014-03-20 00:00:00;"Product b";"1"
2014-03-20 00:00:00;"Product a";"2"
2014-03-20 00:00:00;"Product c";"2"
2014-03-20 00:00:00;"Product b";"25"

我可以重现这个日期为列,第二列为行,第三列为sqlite中的aggegate函数吗? 结果应该是这样的:

Product      2014-03-19    2014-03-20
Product a        5              2
Product b        1              28
Product c      1825             2

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

您必须进行动态查询,即必须为每个日期生成SQL代码。

首先,获取日期:

SELECT DISTINCT ptDate
FROM Orders
ORDER BY ptDate

然后,从为每个所需产品返回一个记录的查询开始:

SELECT Description AS Product
FROM Products

(如果您想将此限制为某些特定订单中的产品,则必须在此处进行加入,或使用WHERE PtUnique IN (...)。)

然后编写一个查询,将这些产品与每个日期的一列组合在一起。 必须使用相关子查询计算这些值:

SELECT Description AS Product,
       (SELECT SUM(OrderDetails2.Quantity)
        FROM OrderDetails2
        JOIN Orders ON OrderDetails2.PtOrder = Orders._id
        WHERE Orders.ptDate = '2014-03-19'
          AND OrderDetails2.PtProduct = Products.PtUnique
       ) AS "2014-03-19",
       (SELECT SUM(OrderDetails2.Quantity)
        FROM OrderDetails2
        JOIN Orders ON OrderDetails2.PtOrder = Orders._id
        WHERE Orders.ptDate = '2014-03-20'
          AND OrderDetails2.PtProduct = Products.PtUnique
       ) AS "2014-03-20"
FROM Products