使用具有匹配ID的另一个表在查询中的列中插入值

时间:2018-02-11 02:39:59

标签: sql sql-server tsql

我有两张桌子:

Cust360

Customer_id int primary key,
Gender nvarchar(50),
Basket_count int null,

交易

Cust_id int,
Transaction_id int,
tran_date datetime,
total_amt int

我必须在Transactions表中的Basket_count中插入值 DISTINCT购买的数量,其中一天内多次购买等于1个购物篮。

SELECT COUNT(tran_date)
FROM Transactions
GROUP BY tran_date, cust_id
HAVING COUNT(tran_date) > 1

我想在cust360的Basket_count列中插入这些值 来自cust_id的{​​{1}}与cust360的transactions匹配。

1 个答案:

答案 0 :(得分:1)

您需要在INNER JOINUPDATE的{​​{1}}语句中执行Customer_id。您已将问题标记为Cust_idMySQL RDBMS,因此结构略有不同。

MySQL示例:

SQL Server

SQL Server(Transact / T-SQL)示例:

UPDATE Cust360 c
INNER JOIN (
    SELECT Cust_id, COUNT(t.tran_date) cnt
    FROM Transactions t
    GROUP BY t.tran_date, t.cust_id
    HAVING COUNT(tran_date) > 1) t2 ON c.Customer_id = t2.Cust_id
SET c.Basket_count = t2.cnt;

[SEE MySQL DEMO HERE]

[SEE TSQL DEMO HERE]

enter image description here

此外,假设您现在要收集UPDATE c SET c.Basket_count = t2.cnt FROM Cust360 c INNER JOIN ( SELECT Cust_id, COUNT(t.tran_date) cnt FROM Transactions t GROUP BY t.tran_date, t.cust_id HAVING COUNT(tran_date) > 1) t2 ON c.Customer_id = t2.Cust_id 的{​​{1}},您可以在名为SUM()的Cust360表中添加一列,然后:

MySQL示例:

total_amt

SQL Server(Transact / T-SQL)示例:

TotalAmount

enter image description here