我需要设置一个查询来运行每个销售团队的销售报表。以下简化模型涉及三个表。
SQL FIDDLE HERE: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和最低可能的date_joined团队,大于transaction_date
**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
我没有要求整个查询,只是根据小于某个指定日期的最高日期加入数据的一些帮助。
谢谢!
答案 0 :(得分:1)
这样的事情:
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
如果您真的想要&lt;#strong; 最低可能的date_joined团队更强而不是transaction_date&#34;,请更改
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