SQL - 在同一个表中乘以值

时间:2017-10-11 16:55:40

标签: sql select sql-server-2005

我有以下代码:

SELECT ConsumerID, Product,
       (frequency * Product_Value) as Value_productA
       (frequency * Product_Value) as Value_productB
       (frequency * Product_Value) as value_productC
From Table1

table1看起来像这样:

ConsumerID | Product | Product_value | frequency | value_productA | value_productB | value_productC
-----------------------------------------------------------------
001 | productA | 5$ | 2 | | | |
001 | productB | 7$ | 4 | | | |
001 | productC | 9$ | 6 | | | |
002 | productA | 5$ | 2 | | | |
002 | productB | 7$ | 4 | | | |
002 | productC | 9$ | 6 | | | |


Expected Bevaviour:

ConsumerID | Product | Product_value | frequency | value_productA | value_productB | value_productC
-----------------------------------------------------------------
001 | productA | 5$ | 2 |10$ |    |    |
001 | productB | 7$ | 4 |    |28$ |    |
001 | productC | 9$ | 6 |    |    |54$ |
002 | productA | 5$ | 2 | 10$|    |    |
002 | productB | 7$ | 4 |    |28$ |    |
002 | productC | 9$ | 6 |    |    |54$ |


Current behaviour:

ConsumerID | Product | Product_value | frequency | value_productA | value_productB | value_productC
-----------------------------------------------------------------
001 | productA | 5$ | 2 |10$ |10$ |10$ |
001 | productB | 7$ | 4 |28$ |28$ |28$ |
001 | productC | 9$ | 6 |54$ |54$ |54$ |
002 | productA | 5$ | 2 |10$ |10$ |10$ |
002 | productB | 7$ | 4 |28$ |28$ |28$ |
002 | productC | 9$ | 6 |54$ |54$ |54$ |

我们的想法是计算每个客户的价值。 product - 含义频率* product_value。示例代码正确计算SUM,但是将其写入每个fiels而不是仅在value_productX字段中。

1 个答案:

答案 0 :(得分:0)

您需要一些条件逻辑,例如case

SELECT ConsumerID, Product,
       (case when product = 'productA' then (frequency * Product_Value) end) as Value_productA
       (case when product = 'productB' then (frequency * Product_Value) end) as Value_productB
       (case when product = 'productC' then (frequency * Product_Value) end) as value_productC
From Table1;

通常,当提出类似问题时,目标是每consumerid行获得一行。如果是这种情况,您需要聚合:

select ConsumerID,
       sum(case when product = 'productA' then (frequency * Product_Value) end) as Value_productA
       sum(case when product = 'productB' then (frequency * Product_Value) end) as Value_productB
       sum(case when product = 'productC' then (frequency * Product_Value) end) as value_productC
From Table1
group by ConsumerID