SELECT type, count(*) as Total
FROM table
WHERE date between ((YEAR(CURDATE())-1900)*1000+DAYOFYEAR(CURDATE())-30)
AND (YEAR(CURDATE())-1900)*1000+DAYOFYEAR(CURDATE())
AND rp=100
AND pd in ('P7','P9','QU','QL')
GROUP BY type;
这会产生:
**TYPE** **TOTAL**
A 2
B 4
编辑我的查询是否可行,给我一个像A /(A + B)这样的百分比。我正在努力将单一类型的总值作为分子,并将所有类型的总值作为分母
答案 0 :(得分:0)
简单版本,使用子查询返回表格总行数的cte:
with cte as
(
select type
from table
where date between ((year(CURDATE())-1900)*1000+DAYOFYEAR(CURDATE())-30)
and (year(CURDATE())-1900)*1000+DAYOFYEAR(CURDATE())
and rp = 100
and pd in ('P7', 'P9', 'QU', 'QL')
)
select type, count(*), 100.0 * count(*) / (select count(*) from cte)
from cte
group by type
答案 1 :(得分:0)
最简单明了的是:
select type
, count(*) / (
select count(*)
from table
where date between ((year(CURDATE())-1900)*1000+DAYOFYEAR(CURDATE())-30)
and (year(CURDATE())-1900)*1000+DAYOFYEAR(CURDATE())
and rp=100
and pd in ('P7','P9','QU','QL')
) as TotalFraction
from table
where date between ((year(CURDATE())-1900)*1000+DAYOFYEAR(CURDATE())-30)
and (year(CURDATE())-1900)*1000+DAYOFYEAR(CURDATE())
and rp=100
and pd in ('P7','P9','QU','QL')
group by type;
虽然你可能想利用CTE或临时表来避免重复条件。
答案 2 :(得分:0)
我会做类似以下的事情,我想你需要根据你的数据做一些改变
select sum(case when type = 'A' then 1 else 0 end) /
(sum(case when type = 'A' then 1 else 0 end) + sum(case when type = 'B' then 1 else 0 end)) as Ratio
from table
where date between ((year(CURDATE())-1900)*1000+DAYOFYEAR(CURDATE())-30)
and (year(CURDATE())-1900)*1000+DAYOFYEAR(CURDATE())
and rp=100
and pd in ('P7','P9','QU','QL') ;
答案 3 :(得分:0)
SELECT type, Total, CONVERT(decimal, Total)/SUM(Total) OVER() AS Percentage
FROM
(
SELECT type, count(*) as Total
FROM table
WHERE date between ((YEAR(CURDATE())-1900)*1000+DAYOFYEAR(CURDATE())-30)
AND (YEAR(CURDATE())-1900)*1000+DAYOFYEAR(CURDATE())
AND rp=100
AND pd in ('P7','P9','QU','QL')
GROUP BY type
) TYPES