![](/img/trans.png)
[英]MySQL - One to Many Join - Return results for only 1 row from “One” table
[英]Table join to return results in one row.
我有两个表,需要创建一个 mysql 视图,在一行中提供结果。
目前我使用连接,但它为我提供了行而不是列的记录。 我尝试了枢轴,但无法使其正常工作。 我需要连续工作的油漆时间,铅垂时间和其他(其他所有内容都在其他)。
表结构在这里:
这基本上是一个PIVOT
,不幸的是 MySQL 没有 PIVOT 函数,但您可以使用带有CASE
语句的聚合函数:
select jobnum,
sum(case when tasktype = 'paint' then hrs else 0 end) Paint,
sum(case when tasktype = 'plumb' then hrs else 0 end) plumb,
sum(case when tasktype not in ('paint', 'Plumb') then hrs else 0 end) Other
from tablea a
left join tableb b
on a.id = b.tbla_id
group by jobnum
结果:
| JOBNUM | PAINT | PLUMB | OTHER |
----------------------------------
| 1 | 10 | 10 | 20 |
| 2 | 25 | 0 | 0 |
SELECT
a.`JobNum`,
SUM(IF(a.`TaskType`='Paint',b.`Hrs`,0)) AS 'Paint',
SUM(IF(a.`TaskType`='Plumb',b.`Hrs`,0)) AS 'Plumb',
SUM(IF(a.`TaskType` IN('Paint','Plumb'),0,b.`Hrs`)) AS 'Other'
FROM `tableA` a
INNER JOIN `tableB` b
ON b.`tblAid`=a.`id`
GROUP BY a.`JobNum`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.