在SQL中将行转换为列

时间:2019-03-22 09:03:46

标签: mysql sql

考虑带有模式的表

orders(user int, amount int, created datetime);

只有一行=交易,我想按用户查询交易数据组

例如

User    First_Order_Amount    First_Order_DateTime Second_OrderAmount    Second_Order_DateTime
1       21                    2019-01-02           22                    2019-01-03
2       13                    2019-01-04           14                    2019-01-05

SQL小提琴:https://www.db-fiddle.com/f/v4gZUMFbuYorB27AH9yBKy/8

3 个答案:

答案 0 :(得分:1)

如果您使用的是MySQL 8+,也可以使用window functions代替group by

SELECT user, amount, created FROM
(SELECT * ,
ROW_NUMBER() OVER (PARTITION BY user ORDER BY user) AS rn
from orders) t
where t.rn = 1

答案 1 :(得分:0)

您可以为此使用嵌套查询,例如:

SELECT o.user,
(SELECT o1.amount FROM orders o1 WHERE o1.user = o.user AND o1.created = (SELECT MIN(created) FROM orders WHERE user = o1.user)) AS first_order_amount,
(SELECT MIN(created) FROM orders o1 WHERE o1.user = o.user) AS first_order_datetime, 
(SELECT o1.amount FROM orders o1 WHERE o1.user = o.user AND o1.created = (SELECT MIN(created) FROM orders o1 WHERE o1.user = o.user AND o1.created > (SELECT MIN(created) FROM orders WHERE user = o1.user))) AS second_order_amount,
(SELECT MIN(created) FROM orders o1 WHERE o1.user = o.user AND o1.created > (SELECT MIN(created) FROM orders WHERE user = o1.user)) AS second_order_datetime
FROM orders o
GROUP BY o.user;

这是 SQL Fiddle

答案 2 :(得分:0)

在MySQL 8+中,您可以使用窗口函数和条件聚合:

select o.user,
       max(case when seqnum = 1 then amount end) as first_order_amount,
        max(case when seqnum = 1 then created end) as first_order_datetime,
       max(case when seqnum = 2 then amount end) as second_order_amount,
       max(case when seqnum = 2 then created end) as second_order_datetime
from (select o.*,
             row_number() over (partition by user order by created) as seqnum
      from orders o
     ) o
group by o.user;