SQL查询提取平均数量

时间:2018-02-20 03:44:22

标签: sql sql-server

我想计算一篮子客户购买的平均数量 (1篮子= 1天内购买多件商品) 从表事务中将其更新为cust360.average_basket_Qty

交易: -

Trasactions_ID  cust_id   Tran_date                       Qty   Total_amt

80712190438     270351    2014-02-28 00:00:00.000          5     4265.3 

29258453508     270384    2014-02-27 00:00:00.000          5     8270.925

51750724947     273420    2014-02-24 00:00:00.000          2     1748.11

93274880719     271509    2014-02-24 00:00:00.000          3     4518.345

51750724947     273420    2014-02-23 00:00:00.000          2     1748.11

97439039119     272357    2014-02-23 00:00:00.000          2     1821.04

45649838090     273667    2014-02-22 00:00:00.000          1     1602.25

Cust360表: -

   Cust_id   Gender   Age    Basket_count  Total_sale      Date        Average_basket_Qty

   266783    M     525         0            3113     2013-02-20         NULL

   266784    F     314         1            5694     2012-12-04         NULL

   266785    F     392         0           21613     2013-08-01         NULL

   266788    F     551         0           6092      2013-02-12         NULL

   266794    F     564         1           27981     2014-02-12         NULL 

1 个答案:

答案 0 :(得分:0)

以下查询应该适合您

UPDATE DEST
SET DEST.Average_basket_Qty = SRC.AVG_QTY
FROM Cust360  DEST
INNER JOIN
(
   SELECT CUST_ID, CAST(TRAN_DATE AS DATE), AVG(QTY) AVG_QTY
   FROM Transactions
   GROUP BY CUST_ID,CAST(TRAN_DATE AS DATE)
) SRC ON SRC.CUST_ID=DEST.Cust_id