我有以下SQL
SELECT
i.si_num AS `id`,
DATE_FORMAT(i.si_date, '%d-%b-%Y') AS `date`,
i.si_tr AS `tr`,
d.dl_name AS `customer`,
i.si_net_value AS `net`,
DATEDIFF(CURDATE(), si_date) AS Days,
t.value AS tval,
t.label AS label
FROM
invoices AS i
LEFT JOIN
dealer AS d ON i.si_tr = d.dl_id
LEFT JOIN
transactions AS t ON i.si_num = t.invoice
WHERE
i.si_tr = 'TR580494'
ORDER BY `si_num` DESC;
电流输出
+-----+-----------+----------+---------------------+---------+------+-------+-------+
| id | date | tr | customer | net | Days | tval | label |
+-----+-----------+----------+---------------------+---------+------+-------+-------+
| 404 | 18-Feb-17 | TR580494 | STARSHIP ENTERPRISE | 109790 | 55 | 96070 | acr |
| 404 | 18-Feb-17 | TR580494 | STARSHIP ENTERPRISE | 109790 | 55 | 10080 | crn |
| 404 | 18-Feb-17 | TR580494 | STARSHIP ENTERPRISE | 109790 | 55 | 3640 | crn |
| 240 | 13-Feb-17 | TR580494 | STARSHIP ENTERPRISE | 0 | 60 | NULL | NULL |
| 239 | 13-Feb-17 | TR580494 | STARSHIP ENTERPRISE | 81975 | 60 | 30405 | acr |
| 239 | 13-Feb-17 | TR580494 | STARSHIP ENTERPRISE | 81975 | 60 | 51570 | crn |
| 132 | 3-Feb-17 | TR580494 | STARSHIP ENTERPRISE | 38132.5 | 70 | 33282 | acr |
+-----+-----------+----------+---------------------+---------+------+-------+-------+
如您所见,正在生成一些重复的行,例如id:404&239
这些行中的唯一区别是“ tval”和“ label”列中的值
'tval'和'label'列可以为每个id填充多次,我想要实现的是针对每个重复的记录,我想查看标签是'crn'还是'arc'并分别求和到id并生成一行并将标签转置为列。请参阅下面的预期输出。
预期产量
+-----+-----------+----------+---------------------+---------+------+-------+-------+
| id | date | tr | customer | net | days | crn | acr |
+-----+-----------+----------+---------------------+---------+------+-------+-------+
| 404 | 18-Feb-17 | TR580494 | STARSHIP ENTERPRISE | 109790 | 55 | 13720 | 96070 |
| 240 | 13-Feb-17 | TR580494 | STARSHIP ENTERPRISE | 0 | 60 | NULL | NULL |
| 239 | 13-Feb-17 | TR580494 | STARSHIP ENTERPRISE | 81975 | 60 | 51570 | 30405 |
| 132 | 3-Feb-17 | TR580494 | STARSHIP ENTERPRISE | 38132.5 | 70 | NULL | 33282 |
+-----+-----------+----------+---------------------+---------+------+-------+-------+
最佳答案
您可以在case
中使用sum
来实现:
SELECT
i.si_num AS `id`,
DATE_FORMAT(i.si_date, '%d-%b-%Y') AS `date`,
i.si_tr AS `tr`,
d.dl_name AS `customer`,
i.si_net_value AS `net`,
DATEDIFF(CURDATE(), si_date) AS Days,
sum(case when t.label = 'acr' then t.value else null end) as acr
sum(case when t.label = 'crn' then t.value else null end) as crn
FROM
invoices AS i
LEFT JOIN
dealer AS d ON i.si_tr = d.dl_id
LEFT JOIN
transactions AS t ON i.si_num = t.invoice
WHERE
i.si_tr = 'TR580494'
GROUP BY i.si_num,
DATE_FORMAT(i.si_date, '%d-%b-%Y'),
i.si_tr,
d.dl_name,
i.si_net_value,
DATEDIFF(CURDATE(), si_date)
ORDER BY `si_num` DESC;
关于mysql - 列出所有数据,合并重复的行并使用MySQL求和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43412342/