我正在转动我的查询,现在我有以下查询:
select
ad_st_id_state,
round(IF(id_brand = 72, avg(if(id_brand = 72, vp_retail, null)), null),2) AS 'PRODUCT 1',
round(IF(id_brand = 75, avg(if(id_brand = 75, vp_retail, null)), null),2) AS 'PRODUCT 2'
from sf_product
join sf_brand on fa_ba_id_brand = id_brand
where vi_pr_id_proyect = 5
GROUP BY
id_brand, ad_st_id_state
我得到的结果计算得很好,我得到了我的结果集:
ad_st_id_state | PRODUCT 1 | PRODUCT 2
7 24.05 null
19 23.91 null
23 23.38 null
7 null 27.37
19 null 24.68
23 null 24.46
7 null null
19 null null
23 null null
7 null null
19 null null
23 null null
但我希望结果集为:
ad_st_id_state | PRODUCT 1 | PRODUCT 2
7 24.05 27.37
19 23.91 24.68
23 23.38 24.46
我一直试图通过不同的组合修改组来获得这个,但我不能这样做。有些人可以帮助我,告诉我为什么你的答案有效,所以我能理解我做错了什么?
感谢
答案 0 :(得分:1)
我会写这样的查询:
select ad_st_id_state,
avg(case when id_brand = 72 then vp_retail end) as Brand_72,
avg(case when id_brand = 75 then vp_retail end) as Brand_75
from sf_product join
sf_brand
on fa_ba_id_brand = id_brand
where vi_pr_id_proyect = 5
group by ad_st_id_state;