在别名上划分:sql

wooyq4lh  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(361)

这个问题在这里已经有答案了

在sql计算中使用别名(4个答案)
两年前关门了。
希望将returned和total列分开,以获得退货最多的产品的退货率。下面是我的例子,如何在别名上添加除法函数?

SELECT brand
    ,model
    ,count(*) Total
    ,sum(case when returned = 'Y' then 1 else 0 end) as Returned
    ,sum(case when returned = '' then 1 else 0 end) as Kept

FROM table
WHERE year= '2018'
AND NOT type = 's'
GROUP by model

ORDER by Returned DESC;

谢谢

wbrvyc0a

wbrvyc0a1#

你可以把它包在另一个里面 SELECT ```
SELECT brand
,model
,count(*) Total
,sum(case when returned = 'Y' then 1 else 0 end) as Returned
,sum(case when returned = '' then 1 else 0 end) as Kept
,(SELECT Returned/Total) as Rate
FROM table
WHERE year= '2018'
AND NOT type = 's'
GROUP by model
ORDER by Returned DESC;

js81xvg6

js81xvg62#

你可以这么做。

SELECT brand
    ,model
    ,count(*) as Total
    ,sum(case when returned = 'Y' then 1 else 0 end) as Returned
    ,sum(case when returned = 'Y' then 1 else 0 end)/count(*) as returnRate
    ,sum(case when returned = '' then 1 else 0 end) as Kept

FROM table
WHERE year= '2018'
AND NOT type = 's'
GROUP by model
ORDER by Returned DESC;

相关问题