mysql - 根据最低出现值构建表和连接记录

标签 mysql sql join

我需要设置一个查询来运行每个销售团队的销售报告。下面的简化模型涉及到三个表。

此处的 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/

相关文章:

mysql - Nodejs 在函数执行之间等待

mysql - 需要替代方案来从同一个表上的插入触发器插入第二个数据行

sql - 我想通过使用特定列进行分组,但同时我需要连接

java - 如何比较 SQL where 条件中的两个逻辑表达式?

MySQL 加入子查询

mysql - MySQL 中何时使用单引号、双引号和反引号

php - DATE_FORMAT(库存日期时间 ,'%Y-%m-%d')

mysql - 为什么 "marks < max(marks)"不起作用

.net - 为什么在简单的一对多关系上使用LINQ Join?

sql - Postgres - DELETE JOIN,USING 给出错误