char变量的相对值

时间:2014-11-17 17:03:50

标签: sql char relative

我的表格值为"是","否"和" N / A"对于变量ORGANIC 我可以单独找到其中一个的百分比,但我不会是一个有百分比的表,是和否和N / A

如果只是是或否,我知道该怎么做

select (1-Cast(t.yes as dec(32,2))/Count(*)) as no, 
  Cast(t.yes as dec(32,2))/Count(*) as yes, t.yes
from Products ,
  (Select Count(organic) as yes from Products
   where organic = 'yes') t

group by yes

问题在于它有两个以上的结果

任何帮助?

2 个答案:

答案 0 :(得分:0)

这里有两个选项。

这个考虑表中的所有选项但使用子查询:

SELECT Organic, COUNT(*) AS Quantity, 100.0 * COUNT(*) / (SELECT COUNT(*) FROM Products)
FROM Products
GROUP BY Organic

这个只考虑树选项但不使用子查询:

SELECT
100.0 * COUNT(CASE WHEN Organic = 'yes' THEN 1 END) / COUNT(*) AS Yes,
100.0 * COUNT(CASE WHEN Organic = 'no' THEN 1 END) / COUNT(*) AS No,
100.0 * COUNT(CASE WHEN Organic = 'N/A' THEN 1 END) / COUNT(*) AS NA
FROM Products

答案 1 :(得分:-1)

你可以这样做:

select
  a.organic,a.groupedcount/b.totalcount * 100 as percentage
from 
(select organic,count(*) groupedcount 
 from products 
 group by organic) a,
(select count(*) totalcount 
 from products) b

或者如果您不想使用ANSI-89:

select
  a.organic,a.groupedcount/b.totalcount * 100 as percentage
from 
(select organic,count(*) groupedcount 
 from products 
 group by organic) a 
CROSS JOIN (select count(*) totalcount 
 from products) b

将给出完全相同的结果