SQL联合和分组

我有一个查询:


SELECT users.name, 

COUNT(DISTINCT leads.id) as leads,

COUNT(DISTINCT properties.id) as properties,

COUNT(DISTINCT buyers.id) as buyers,

null

FROM users

LEFT JOIN (SELECT * from leads WHERE date(created_at) BETWEEN '2019-04-13' AND'2019-04-13') leads ON users.id = leads.user_id

LEFT JOIN (SELECT * from properties WHERE date(contract_start_date) BETWEEN '2019-04-13' AND'2019-04-13') as properties ON users.id = properties.user_id

LEFT JOIN (SELECT * from buyers WHERE date(created_at) BETWEEN '2019-04-13' AND'2019-04-13') as buyers ON users.id = buyers.user_id

LEFT JOIN buyer_searches ON buyers.id = buyer_searches.buyer_id

GROUP BY users.id

UNION

SELECT users.name,

null, null, null,

COUNT(DISTINCT buyer_searches.id) as buyer_searches

FROM users

LEFT JOIN buyers ON users.id = buyers.user_id

LEFT JOIN (SELECT * from buyer_searches WHERE date(created_at) BETWEEN '2019-04-08' AND'2019-04-13') as buyer_searches ON buyers.id = buyer_searches.buyer_id

GROUP BY users.id

我得到的表格中当然有重复的用户,但参数正确:


users field1 field2 field3 etc....

user1 data . null . null etc...

user2 data . null . null etc...

user1 null . data . data etc...

user2 null . data .data etc...

etc...

我想按用户连接行。


Qyouu
浏览 141回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP