gpt4 book ai didi

mysql - 将一列转置为mysql中的三个新列

转载 作者:行者123 更新时间:2023-11-29 05:53:57 24 4
gpt4 key购买 nike

我在 mysql 中有一个表,其中包含以下列:

enter image description here

数据示例:

'16', '1', 'Evening', '6.00', '2014-06-05 08:14:35', '2014-06-04', '6.00'
'17', '2', 'Afternoon', '8.00', '2014-06-05 08:15:29', '2014-06-04', '8.00'
'18', '3', 'Afternoon', '4.00', '2014-06-05 08:17:32', '2014-06-04', '4.00'
'19', '4', 'Afternoon', '4.00', '2014-06-05 08:18:25', '2014-06-04', '4.00'
'20', '17', 'Morning', '2.00', '2014-06-05 09:11:40', '2014-06-05', '2.00'
'21', '17', 'Morning', '3.00', '2014-06-05 09:16:36', '2014-06-04', '3.00'
'22', '17', 'Evening', '2.00', '2014-06-05 09:17:43', '2014-06-04', '2.00'
'23', '19', 'Morning', '1.00', '2014-06-05 10:12:47', '2014-06-05', '1.00'
'24', '20', 'Morning', '2.00', '2014-06-05 10:16:02', '2014-06-05', '2.00'
'25', '22', 'Morning', '2.00', '2014-06-05 10:27:34', '2014-06-05', '2.00'
'26', '23', 'Morning', '2.00', '2014-06-05 10:28:08', '2014-06-05', '2.00'
'27', '24', 'Morning', '1.00', '2014-06-05 10:30:20', '2014-06-05', '1.00'
'28', '27', 'Morning', '1.00', '2014-06-05 10:43:12', '2014-06-05', '1.00'
'29', '27', 'Combined', '2.00', '2014-06-05 10:45:45', '2014-06-04', '2.00'
'31', '28', 'Morning', '3.00', '2014-06-05 11:04:32', '2014-06-05', '3.00'

我想转置时间列,这样我就有了晚上、下午和早上三个新列,并记录数量,使列看起来像
id、cow_id、Evening、Afternoon、Morning、date_added、date、quantity_type

有人可以给我一个关于如何使用 mysql 查询解决这个问题的解决方案吗?

最佳答案

如果你想在一行中包含给定日期的所有奶牛饲料,你可以尝试这样的事情:

SELECT cow_id, 
SUM(CASE time WHEN 'Evening' THEN quantity ELSE 0 END) AS Evening,
SUM(CASE time WHEN 'Afternoon' THEN quantity ELSE 0 END) AS Afternoon,
SUM(CASE time WHEN 'Morning' THEN quantity ELSE 0 END) AS Morning,
SUM(CASE time WHEN 'Combined' THEN quantity ELSE 0 END) AS Combined,
`date`
FROM cows
GROUP BY cow_id, date

对于您的示例数据,这将给出如下结果(请注意,我必须为“合并”时间添加另一列):

cow_id  Evening Afternoon   Morning Combined    date    
1 6 0 0 0 2014-06-04
2 0 8 0 0 2014-06-04
3 0 4 0 0 2014-06-04
4 0 4 0 0 2014-06-04
17 2 0 3 0 2014-06-04
17 0 0 2 0 2014-06-05
19 0 0 1 0 2014-06-05
20 0 0 2 0 2014-06-05
22 0 0 2 0 2014-06-05
23 0 0 2 0 2014-06-05
27 0 0 0 2 2014-06-04
27 0 0 1 0 2014-06-05
28 0 0 3 0 2014-06-05

关于mysql - 将一列转置为mysql中的三个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51492833/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com