我需要设置一个查询来运行每个销售团队的销售报告。下面的简化模型涉及到三个表。
此处的 SQL FIDDLE:http://sqlfiddle.com/#!9/b09b3a/
**users_table**
id name
1 John Doe
**sales_team**
user_id sales_team date_joined_team
1 Sales team 1 Jan 1st
1 Sales team 2 Jan 5th
1 Sales team 3 Jan 10th
1 Sales team 2 Jan 15th
**transactions**
user_id transaction_date amount
1 Jan 2nd 20.00
1 Jan 3rd 10.00
1 Jan 7th 15.00
1 Jan 11th 13.00
1 Jan 16th 5.00
我需要加入交易表上正确的销售团队,使用用户 ID 和每笔交易大于 transaction_date 的最低可能 date_joined 团队
**desired results**
sales_team date amount
Sales team 1 Jan 2nd 20.00
Sales team 1 Jan 3rd 10.00
Sales team 2 Jan 7th 15.00
Sales team 3 Jan 11th 13.00
Sales team 2 Jan 16 5.00
我并不是要求提供整个查询,只是要求提供有关如何基于小于某个指定日期的最高日期联接数据的一些帮助。
谢谢!
最佳答案
类似这样的事情:
select date, amount, (
select st.sales_team
from sales_team st
where st.user_id = t.user_id
and st.date_joined_team < t.date
order by st.date_joined_team desc
limit 1) as sales_team
from transactions t
如果您确实想要“最低加入日期大于大于 transaction_date 的团队”,请更改
and st.date_joined_team < t.date
order by st.date_joined_team desc
至
and st.date_joined_team > t.date
order by st.date_joined_team asc
关于mysql - 根据最低出现值构建表和连接记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45313132/