SQL Query SELECT和Group by条件

时间:2016-01-13 00:13:14

标签: mysql sql

我有一个叫做项目表的表。

示例内容:

order           product    plan qty price   term    base_price
CO0300039921    ZZFEE0000   N   1   0.01    1       25
CO0300039921    ZZFEE0000   N   1   0.01    1       37.13
CO0300039921    ZZFEE0000   N   1   0.02    1       37.13
CO0300039921    ZZFEE0000   Y   1   0       1       1
CO0300039921    ZZFEE0000   Y   1   0       1       1
AO1000301407    VOSVC0002W0 Y   1   0       1       3
AO1000301407    VOACT0101   N   1   0       2       5.99


If plan is ‘N’ Then
    get SUM(qty) AS 'quantity'
    get price AS 'rate'
If plan is ‘Y’ Then
    get SUM(qty) AS 'quantity'
    get (term * qty) AS 'rate'
    get (base_price) AS 'base'

FROM item
WHERE order = 'CO0300039921'
GROUP BY product, price, base_price

预期结果:

 order           product    plan qty  price rate  base_price  
    CO0300039921    ZZFEE0000   N   2    0.01  0.01     -
    CO0300039921    ZZFEE0000   N   1    0.02  1        -
    CO0300039921    ZZFEE0000   Y   2    -     1        1 

以下是我尝试的内容:

SELECT CASE WHEN p8_plus_plan = 'Y' THEN 
( 

   SUM(qty_ordered),
   (p8_contract_term*qty_ordered) AS 'rate',
   product_base_price
)
ELSE 
( 
   SUM(qty_ordered),
   price AS 'rate'
)
END
FROM ns_order_line 
WHERE order_no = ? 
GROUP BY product_id, price, p8_plus_plan, product_base_price, order_no; 

但我有错误。请帮忙。

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合来完成此操作。像这样:

select sum(case when plan = 'N' then qty end) as N_qty,
       sum(case when plan = 'N' then price end) as N_rate,
       sum(case when plan = 'Y' then qty end) as Y_qty,
       sum(case when plan = 'Y' then term*qty end) as Y_rate,
       sum(case when plan = 'Y' then base_price end) as Y_base
from item
where order = 'CO0300039921'
group by product;

我不确定你真正想要聚合的是什么。但关键的想法是聚合函数中的case

答案 1 :(得分:1)

我想象的那样。

SELECT
      `order`
    , `product`
    , `plan`
    , CASE WHEN `plan` = 'Y' THEN base_price END AS base /* edit due to comment */
    , SUM(qty) AS qty
    , MAX(price) AS price
    , SUM(CASE WHEN `plan` = 'N' THEN price
               WHEN `plan` = 'Y' THEN (term * qty) END) AS rate
FROM item
WHERE `order` = 'CO0300039921'
GROUP BY
      `order`
    , `product`
    , `plan`
    , CASE WHEN `plan` = 'Y' THEN base_price END

btw:列名“order”不是一个好选择,因为它是一个保留字,也经常使用。在引用该列时需要使用反引号。

可以使用没有聚合函数的CASE EXPRESSION,但那个case表达式必须*也是GROUP BY子句的一部分。

*在MySQL(仅限)中你可以绕过这个,因为MySQL有一个不寻常的“扩展”来按语法分组,但这可以通过服务器设置改变,依赖于该扩展是有风险的。我强烈建议您将所有列(包括案例表达式)包含在不使用聚合函数的group by子句中(sum / count / avg等)