如何选择特定月份具有相同范围价格的产品?

时间:2016-04-28 04:33:25

标签: mysql sql

我有一个包含项目的表:

ProductId  Month  range_prc   Price   Region
   1001      1      101         88      10
   1002      1      100         44      10
   1003      1      100         34      20
   1001      2       88         88      10
   1002      2      100         54      10
   1003      2      100         34      20
   1001      3      100         33      10
   1002      3      100         23      10
   1003      3      100         13      20
   1001      4      102         56      20

如何从第1-3个月开始选择range_prc = 100的priductId

这是我到目前为止所尝试的:

    select productId, region, 
    sum(if(mothn =1, range_pr, 0))  AS Jan, sum(if(month = 2, range_pr, 0))  AS feb, 
    sum(if(month= 3, range_pr, 0))  AS Mar
    from table
    where range_pr=100 
group by productId, region

结果是:

ProductId    Region  Jan  Feb   Mar
   1001       10      0    0    100
   1002       10     100  100   100
   1003       20     100  100   100

但我想只显示三个时期内具有相同range_prc的产品,如下所示:

ProductId    Region  Jan  Feb   Mar
  1002       10     100  100   100
  1003       20     100  100   100

1 个答案:

答案 0 :(得分:1)

您可以使用HAVING

select productId, region, 
       sum(if(month=1, range_pr, 0)) AS Jan,
       sum(if(month=2, range_pr, 0)) AS Feb, 
       sum(if(month=3, range_pr, 0)) AS Mar
from table
group by productId, region
having Jan = 100 AND Feb = 100 AND Mar = 100;

或者您可以使用子查询:

select *
from (
  select productId, region, 
         sum(if(month=1, range_pr, 0)) AS Jan,
         sum(if(month=2, range_pr, 0)) AS Feb, 
         sum(if(month=3, range_pr, 0)) AS Mar
  from table
  group by productId, region
  ) p
WHERE Jan = 100 AND Feb = 100 AND Mar = 100;