我正在处理一个查询,其中我需要添加一个列,其中的任务名称包含一对多关系中存在的许多数量
这是我的查询
SELECT
e.full_name AS fullName,
t.issue AS issue,
CASE t.state
WHEN 'open' THEN 'open'
WHEN 'pending' THEN 'In progress'
WHEN 'closed' THEN 'closed'
END AS status,
CASE t.scheduled
WHEN TRUE THEN 'scheduled'
WHEN FALSE THEN 'non-scheduled'
END AS scheduled,
d.name AS device,
DATE(t.date_created) AS dateCreated,
DATE(t.last_updated) AS lastUpdate
FROM
tickets t
INNER JOIN
employees e ON t.employee_id = e.id
INNER JOIN
devices d ON d.id = t.device_id
WHERE
MONTHNAME(t.date_created) = 'August'
ORDER BY dateCreated DESC
这是我工作的方案http://sqlfiddle.com/#!9/39bf3e/1
我尝试按添加计数和组,但此时我猜测
我期待一个看起来像这样的结果
感谢您的帮助
答案 0 :(得分:1)
使用类似的派生表:
SELECT ...
TotalTasks --Add the count column to your select
FROM ticket t
JOIN (SELECT ticked_id, COUNT(1) as TotalTasks
FROM tasks
GROUP BY ticked_id) ta ON t.id = ta.ticked_id
...rest of query
以下是包含整个查询的fiddle
这里的概念是在许多表上进行聚合,然后再加入 one 表。这可确保1-1加入,最好地防止不必要的重复。
答案 1 :(得分:0)
左边加入2表并同时计算,这是查找一对多关系中有多少条目的基础