代码之家  ›  专栏  ›  技术社区  ›  nmr

在一个表中查找在另一个表中匹配的分组记录

  •  0
  • nmr  · 技术社区  · 6 年前

    我在蜂房里有两张像下面这样的桌子

    +----+----------+----------+-----------+
    | id | subject  |   date   |     amount|
    +----+----------+----------+-----------+
    |  1 | Do this  | 10-10-13 |     20985 |
    |  2 | Done this| 10-10-13 |     18657 |
    |  3 | Dont do  | 12-12-13 |     22039 |
    +----+----------+----------+-----------+
    

    表2:

    +----+----------+----------+-----------+
    | id | subject  |   date   |     amount|
    +----+----------+----------+-----------+
    |  1 | Do this  | 10-10-13 |     10985 |
    |  2 | Done this| 10-10-13 |     18657 |
    |  3 | Dont do  | 12-12-13 |     22039 |
    |  4 | Do this  | 10-10-13 |     10000 |
    |  5 | Did this | 11-10-13 |     30000 |
    +----+----------+----------+-----------+
    

    group by subject and date subject and date are Do this and 10-10-13 我得到的总数是一样的。

    table 2 正在分组以匹配中的分组金额 table 1

    我想要的结果是

    +----+----------+----------+-----------+
    | id | subject  |   date   |     amount|
    +----+----------+----------+-----------+
    |  1 | Do this  | 10-10-13 |     10985 |
    |  2 | Done this| 10-10-13 |     18657 |
    |  3 | Dont do  | 12-12-13 |     22039 |
    |  4 | Do this  | 10-10-13 |     10000 |
    +----+----------+----------+-----------+
    

    我怎样才能达到我想要的?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Gordon Linoff    6 年前

    这就是你想要的吗?

    select t2.*
    from (select t2.*,
                 sum(amount) over (partition by date, subject) as total_amount
          from table2 t2
         ) t2 join
         table1 t1
         on t1.date = t2.date and t2.subject = t2.subject and t1.amount = t2.total_amount