更新记录总和

时间:2013-12-27 03:40:53

标签: mysql sql-server group-by sql-update sum

我有一张名为'bill'的表,如下所示:

Cust_id |Bill_amt |Brand |Skincare |Toner |BrandA |BrandB |A_skincare |A_toner |B_skincare |B_toner
001     |100      |A     |50       |50  |NULL   |NULL   |NULL   |NULL   |NULL   |NULL
001     |200      |A     |150      |50  |NULL   |NULL   |NULL   |NULL   |NULL   |NULL
001     |500      |B     |355      |145 |NULL   |NULL   |NULL   |NULL   |NULL   |NULL
009     |325      |B     |125      |200 |NULL   |NULL   |NULL   |NULL   |NULL   |NULL

我想将此表更新为名为'txn'的新表,其中包含以下列:

Cust_id |Value  |BrandA |BrandB |A_skincare |A_toner |B_skincare |B_toner
001     |800    |300    |500    |200        |100     |355        |145 
009     |325    |NULL   |325    |NULL       |NULL    |125        |200

价值是该客户中品牌A和B的总和。 如何将“账单”表更新为“txn”表并显示不同的客户?
为不整洁道歉,非常感谢你。

2 个答案:

答案 0 :(得分:0)

试试这个

create table txn as(select DISTINCT custid,sum(BrandA+BrandB) as value,BrandA,BrandB,A_skincare,B_skincare,B_toner) from bill

答案 1 :(得分:0)

试试这个:

FOR MYSQL ::

UPDATE txn t 
INNER JOIN (SELECT b.Cust_id, SUM(b.Bill_amt) AS `Value`, 
                   SUM(IF(Brand = 'A', b.Bill_amt, 0)) BrandA, SUM(IF(Brand = 'B', b.Bill_amt, 0))BrandB, 
                   SUM(IF(Brand = 'A', b.Skincare, 0)) A_skincare, SUM(IF(Brand = 'B', b.Skincare, 0)) B_skincare, 
                   SUM(IF(Brand = 'A', b.Toner, 0)) A_toner, SUM(IF(Brand = 'B', b.Toner, 0)) B_toner
            FROM bill b 
            GROUP BY b.Cust_id 
           ) AS A ON t.Cust_id = A.Cust_id 
SET t.Value = A.Value, t.BrandA = A.BrandA, t.BrandB = A.BrandB, 
    t.A_skincare = A.A_skincare, t.B_skincare = A.B_skincare, 
    t.A_toner = A.A_toner, t.B_toner = A.B_toner 

FOR SQL SERVER ::

UPDATE t 
SET t.Value = A.Value, t.BrandA = A.BrandA, t.BrandB = A.BrandB, 
    t.A_skincare = A.A_skincare, t.B_skincare = A.B_skincare, 
    t.A_toner = A.A_toner, t.B_toner = A.B_toner 
FROM txn t 
INNER JOIN (SELECT b.Cust_id, SUM(b.Bill_amt) AS `Value`, 
                   SUM(IF(Brand = 'A', b.Bill_amt, 0)) BrandA, SUM(IF(Brand = 'B', b.Bill_amt, 0))BrandB, 
                   SUM(IF(Brand = 'A', b.Skincare, 0)) A_skincare, SUM(IF(Brand = 'B', b.Skincare, 0)) B_skincare, 
                   SUM(IF(Brand = 'A', b.Toner, 0)) A_toner, SUM(IF(Brand = 'B', b.Toner, 0)) B_toner
            FROM bill b 
            GROUP BY b.Cust_id 
           ) AS A ON t.Cust_id = A.Cust_id