这困扰了我一段时间

表:库存

|   customerID   | Item  |  Quantity  |  Price  |
|     cus1       |  A    |     3      |    4    |
|     cus1       |  B    |     2      |    3    |
|     cus1       |  C    |     3      |    3    |
|     cus2       |  A    |     3      |    3.50 |
|     cus2       |  C    |     3      |    2    |
|     cus3       |  D    |     6      |    4    |


如何使我的mysql查询生成如下所示的视图

视图:stock_v

| cusID  | Item |Quan |Price |Tot_Qua | Tot_pri | sumtot_pri/tot_qua|
|  cus1  |  A   |  3  | 4    |   8    | 12      | 3.375             |
|  cus1  |  B   |  2  | 3    |   8    | 6       | 3.375             |
|  cus1  |  C   |  3  | 3    |   8    | 9       | 3.375             |
|  cus2  |  A   |  3  | 3.50 |   6    | 10.05   | 2.675             |
|  cus2  |  C   |  3  | 2    |   6    | 6       | 2.675             |
|  cus3  |  D   |  6  | 4    |   6    | 24      | 4.00              |


cus1的示例。
Cus1具有3个项,即A,B和C。
所以我想要一些公式

Tot_Qua = 3+2+3 = 8
Tot_pri = price x quan


并且Tot_pri必须对此cus1记录求和,

sumtot_pri = (quan x price) + (quan x price) + (quan x price)
sumtot_pri = (12) + (6) + (9)


因为cus1有3个项目,最后一个

sumtot_pri / Tot_qua = 27 / 8 = 3.375


我认为需要分组,因为我想看到他们的项目。我不在乎列tot_qua和列sumtot_pri/tot_qua是否将为每个Cus复制相同的数据。

最佳答案

在MySQL 8+中,您只需使用窗口函数:

select s.*,
       sum(quan) over (partition by cusid) as tot_quan,
       (quan * price) as tot_price,
       sum(quan * price) over (partition by cusid) / sum(quan) over (partition by cusid) as ratio
from stock s;


在早期版本中,您将使用子查询或类似的机制。 joingroup by可能是最简单的:

select s.*, s2.tot_quan, (s.quan * s.price) as tot_price,
       tot_tot_price / tot_quan as ratio
from stock s join
     (select cusid, sum(quan) as tot_quan,
            sum(quan * price) as tot_tot_price
      from stock s2
      group by cusid
     ) s2
     using (cusid);

09-20 03:10