我知道标题是令人厌恶的,但我想不出用简洁的方式来描述我的问题。
我有一张名为onsite_notes
的表格。 onsite_notes
的PK是一个名为onsite_note_id
的字段。我正在努力为每位客户增加所有笔记的时间。目前,我的查询返回某些行的双重条目。我不确定为什么,但它真的很烦人。我想要做的是计算具有特定FK(customer_id)的不同行。这是当前的查询。
SELECT c.searchable_name, co.*, sum(n.time)
as worked_hours_onsite, 'onsite' as type
FROM customers c
LEFT JOIN contracts co on c.customer_id = co.customer_id
LEFT JOIN onsite_tickets t ON t.customer_id = c.customer_id
LEFT JOIN onsite_notes n ON t.onsite_id = n.onsite_id
and (n.date >= 1464760800)
and (n.date < 1467352800)
and (n.isbillable = 1)
WHERE co.contract_type != '' AND
((timestamp(now()) between co.start_date and co.end_date)
OR ((timestamp(now()) <= co.end_date) AND (co.start_date = 0))
OR ((timestamp(now()) >= co.start_date) AND (co.end_date = 0))
OR ((co.start_date = 0) AND (co.end_date=0)))
GROUP BY c.customer_id DESC ) ....
这就是事情的总体思路。它有一个联合的位,但它给了我同样的头痛。基本上,我如何确保为每个客户获得独特的行?我的客户行是唯一的,但汇总的数据并不是唯一的,我希望它是唯一的。
答案 0 :(得分:0)
如果你想要一个总和,你需要一个合适的组,基于你想要分组的行,如果你已经选择了列,你必须将该组扩展到你想要选择的行
..如果您需要明确不要使用
组和最后一组不需要desc .. desc i for order by所以查询应该是这样的事情
SELECT c.searchable_name, co.*, sum(n.time)
as worked_hours_onsite, 'onsite' as type
FROM customers c
LEFT JOIN contracts co on c.customer_id = co.customer_id
LEFT JOIN onsite_tickets t ON t.customer_id = c.customer_id
LEFT JOIN onsite_notes n ON t.onsite_id = n.onsite_id
and (n.date >= 1464760800)
and (n.date < 1467352800)
and (n.isbillable = 1)
WHERE co.contract_type != '' AND
((timestamp(now()) between co.start_date and co.end_date)
OR ((timestamp(now()) <= co.end_date) AND (co.start_date = 0))
OR ((timestamp(now()) >= co.start_date) AND (co.end_date = 0))
OR ((co.start_date = 0) AND (co.end_date=0)))
GROUP BY c.searchable_name, co.*