-1

各期間のこのデータからSQLの結果のパーセンテージを計算したいと思います。

Period  Result
1        Green
1        Blue
1        Blue
1        Red
1        Blue
1        Blue
1        Blue
2        Green 
2        Green 
2        Green
2        Blue
2        Red
2        Red

期待される結果 ..

Period  Result  Percentage
1        Blue     72%
1        Green    9%
1        Red      9%
2        Blue     17%
2        Green    50%
2        Red      33%
4

2 に答える 2

2

COUNTPeriod最初に、結果を元のテーブルと再度結合し、 と の両方でグループ化し、Period除算Resultを行ってパーセンテージを取得します。

SELECT t.Period, t.Result, ((COUNT(t.Result) / Cnt) * 100) Percentage
FROM table t 
     INNER JOIN (SELECT Period, COUNT(*) Cnt
                 FROM table
                 GROUP BY Period) period_cnt 
     ON t.Period = period_cnt.Period
GROUP BY t.Period, t.Result

丸めを調整し、 を使用CONCATして文字を出力に追加する必要がある場合があり%ますが、それはかなり簡単なはずです。

また、最初の期間の平均は間違っています。合計すると になり100ます。Green と Red の値は です14

デモ

于 2012-09-26T21:52:32.090 に答える
1

このようなもの (ANSI SQL):

select period,
       result,
       (count(result) / total_period) * 100 as result_percent
from (
  select period, 
         result,
         count(*) over (partition by period) as total_period
  from periods  
) as t
group by period, total_period, result
order by period, result;

DBMS によっては、小数値を表示するために整数値を 10 進数にキャストする必要がある場合があります。

デモ: http://sqlfiddle.com/#!1/2ec4f/1

于 2012-09-26T22:01:12.680 に答える