我有两张桌子:
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
匹配。
答案 0 :(得分:1)
您需要在INNER JOIN
和UPDATE
的{{1}}语句中执行Customer_id
。您已将问题标记为Cust_id
和MySQL
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;
此外,假设您现在要收集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