您好
我在mysql表中有以下列: rating1,rating2,price,cond,approved
是否可以选择这样的结果:
select
average rating1 + rating2 as total_rating,
average rating1 as rating1,
average rating2 as rating2,
average price if cond = '1' as price_used
average price if cond = '2' as price_new
where approved = '1'
到目前为止,我有:
SELECT
(AVG(t.rating1) + AVG(t.rating2)) / 2 AS total_rating
AVG(t.rating1) AS rating1,
AVG(t.rating2) AS rating2,
---- price statements?? ----
FROM t
WHERE 1=1
AND t.approved = '1'
非常感谢和原谅我的英语
答案 0 :(得分:2)
试试这个:
SELECT (AVG(t.rating1) + AVG(t.rating2)) / 2 AS total_rating,
AVG(t.rating1) AS rating1,
AVG(t.rating2) AS rating2,
AVG(IF(cond='1', price, NULL)) price_used,
AVG(IF(cond='2', price, NULL)) price_new
FROM t
WHERE 1=1
AND t.approved = '1'
编辑:更新了查询以获得所需的结果。
答案 1 :(得分:0)
我不认为在If语句中做一个平均值会起作用。但这是IF的语法。
IF(condition,value_to_display_if_true,value_to_display_if_false)
因此,例如,IF(1 = 1,'true','false')对于此列始终显示'true',因为1确实= 1。
答案 2 :(得分:0)
标准SQL,适用于“所有”主要dbms:
select (avg(t.rating1) + avg(t.rating2)) / 2 as total_rating
,avg(t.rating1) as rating1
,avg(t.rating2) as rating2
,avg(case when cond = '1' then price end) as price_used
,avg(case when cond = '2' then price end) as price_new
from t
where t.approved = '1'