2016-07-06 61 views
0
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)的百分比。我竭力要得到一個單一類型的總價值作爲分子,和所有類型的作爲分母的總價值

+1

標籤與正在使用的數據庫你的問題。 –

回答

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 
+0

所有這些答案都很棒,但我用cte去了。非常感謝!! – mookie

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或臨時表,以避免重複的條件。

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') ; 
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