我需要你的帮助,因为我的SQL级别非常弱,我正在尝试做某些事情但却找不到如何实现它。
假设我有以下行
| Data| Status | Date |
| A | OK | 2017-01-20 |
| B | KO | 2017-01-20 |
| C | OK | 2017-01-20 |
| A | OK | 2017-01-21 |
| B | KO | 2017-01-21 |
| C | KO | 2017-01-21 |
| A | OK | 2017-01-22 |
| B | KO | 2017-01-22 |
| C | OK | 2017-01-22 |
我想查询数据库以获得OK的百分比结果3天,所以它看起来像
A | 100%
B | 0%
C | 66%
我为1个数据做过这个,但是我被卡住了,也许我需要一个循环或其他东西:
Select
Data, (Select Count(*) From DB Where
Date between '2017-01-20' and '2017-01-22'
And Status = 'OK') * 100 / (Select Count(*) From DB
Where Date between '2017-01-20' and '2017-01-22')
From
DB
答案 0 :(得分:4)
试试这个:
SELECT Data, CAST(CAST(AVG((CASE WHEN Status='OK' THEN 100.0 ELSE 0.0 END)) AS INT) AS VARCHAR(MAX)) + '%'
FROM DB
WHERE Date BETWEEN '2017-01-20' AND '2017-01-22'
GROUP BY Data
Try it in Data Explorer *特别感谢@ t-clausen.dk将这个令人敬畏的工具引入我的注意
答案 1 :(得分:3)
SELECT
100*(count(*)-count(nullif(Status,'OK')))/count(*), Data
FROM
<yourtable>
WHERE
Date between'2017-01-20' and '2017-01-22'
GROUP BY
Data
<强> Try it out 强>
答案 2 :(得分:0)
试试这个:
Pay: <select id="pay">
<option value="">Please select</option>
<option value="0">Zero</option>
<option value="1">One</option>
</select>
<input type="text" id="callback" />: <span id="result"></span>
OR
select m.data, ISNULL(((max(tot)*100)/count(m.status)), 0) percentage
from myTable m
LEFT JOIN (select data, count(status) tot from myTable m1 where status ='ok' and date between '2017-01-20' and '2017-01-22' group by m1.data) m2 on m2.data = m.data
where date between '2017-01-20' and '2017-01-22'
group by m.data
答案 3 :(得分:0)
<强>查询强>
select [Data],
((cast((sum(case [Status] when 'OK' then 1 else 0 end)) as decimal(5, 2))) /
cast(count([Data]) as decimal(5, 2))) * 100.00 as perc
from [your_table_name]
where [Date] between '2017-01-20' and '2017-01-22'
group by [Data];