Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 创建具有多个条件的临时表_Sql_Create Table_Temp Tables_With Statement - Fatal编程技术网

Sql 创建具有多个条件的临时表

Sql 创建具有多个条件的临时表,sql,create-table,temp-tables,with-statement,Sql,Create Table,Temp Tables,With Statement,我正在努力创建一个具有多种条件的临时表 让我们把这个主表称为A。我想从这个表中提取数据,将带有上次购买日期和付款日期的不同帐户输出到一个临时表中 +---+--------+-----------+----------+ | | Acct | Trans_Date|Trans_code| +---+--------+-----------+----------+ | 1 | ABC | July 31 | Purchase | | 2 | ABC | Nov 5 | Pa

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

让我们把这个主表称为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子句可能是一种选择,但很难理解。

您可以使用条件聚合:

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

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

您可以使用条件聚合,如下所示:

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。如果我的答案正确回答了你的问题,那么点击复选标记。。。谢谢