【问题标题】:Create a temp table with multiple conditions创建具有多个条件的临时表
【发布时间】:2021-03-18 07:38:18
【问题描述】:

我正在努力创建具有多个条件的临时表。

让我们将此主表称为 A。我想从该表中提取数据,以将具有最后购买日期和付款日期的不同帐户输出到临时表。

+---+--------+-----------+----------+
|   |  Acct  | Trans_Date|Trans_code|
+---+--------+-----------+----------+
| 1 | ABC    | July 31 | Purchase |
| 2 | ABC    | Nov 5   | Payment  |
| 3 | DEF    | Mar 1   | Purchase |
| 4 | ABC    | June 5  | Purchase |
| 5 | GFH    | Feb 7   | Payment  |
| 6 | GFH    | Mar 9   | Purchase |
| 7 | DEF    | Aug 8   | Payment  |
| 8 | GFH    | Mar 9   | Purchase |
| 9 | DEF    | Aug 8   | Payment  |
+---+--------+---------+----------+

输出结果

+---+-------+----------------+--------------+
|   |  Acct | Last_trans_date|Last_transpay |
+---+-------+----------------+--------------+
| 1 | ABC   | July 31        | Nov 5        |
| 2 | DEF   | Mar 1          | Aug 8        |
| 3 | GFH   | Mar 9          | Feb 7        |
+---+------+-----------------+--------------+

我读到使用 WITH 子句可能是一种选择,但很难理解。

【问题讨论】:

    标签: sql create-table temp-tables with-statement


    【解决方案1】:

    您可以像这样使用条件聚合:

    select acct,
        max(case when trans_code = 'Purchase' then trans_date end) as last_purchase,
        max(case when trans_code = 'Payment'  then trans_date end) as last_payment
    from mytable
    group by acct
    

    将查询结果插入另一个表的语法因数据库而异。在其中许多中,您可以使用:

    create table newtable as 
    select ... -- above query
    

    SQL Server 是一个值得注意的例外,您需要:

    select ...
    into newtable
    from ...
    group by ...
    

    【讨论】:

    • 非常感谢。这比我想象的要容易得多。
    • 欢迎@dtman85。如果我的回答正确地回答了您的问题,请点击复选标志accept it...谢谢。
    【解决方案2】:

    您可以使用条件聚合:

    select acct, max(trans_date),
           max(case when trans_code = 'Payment' then trans_date end)
    from t
    group by acct;
    

    然后您可以将其插入到现有表中,或使用适合您数据库的机制将结果另存为新表。

    【讨论】:

      猜你喜欢
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      相关资源
      最近更新 更多