簡體   English   中英

一列上的SQL百分比

[英]SQL percentage on one column

我有一個數據庫,其中列的優先級從1到5,我有列“類別”。 我想計算每個類別中每個優先級總和的百分比。

在這里,您可以看到我的數據庫,我想在哪里獲得每個組的優先級%

示例( 原始圖像 ):

+ ------- + ----------- + ------- + -------- + --- + ----------- + ------ + ------- +
| task_id | name        | notes   | priority | med | category    | status | user_id |
+ ------- + ----------- + ------- + -------- + --- + ----------- + ------ + ------- +
| 6       | erhgbrstdhb | rdthbsr | 1        | Yes | Medications | 0      | 1       |
| 13      | rznhrwd     | hbnrnjr | 2        | Yes | Medications | 1      | 1       |
+ ------- + ----------- + ------- + -------- + --- + ----------- + ------ + ------- +

對於這個例子我應該得到:

優先級1 - 計數1 - %50

優先級5 - 計數1 - %50

我嘗試過但沒有用的( 原始圖片 ):

select  priority,
        count(priority) as priority_count,
        count(priority) * 100.0 / (
            select count(*)
                from tasks
        ) as priority_percent
    from tasks
    where category = "Medications"
    group by priority

+ -------- + -------------- + ---------------- +
| priority | priority_count | priority_percent |
+ -------- + -------------- + ---------------- +
| 1        | 1              | 10.0             |
| 5        | 1              | 10.0             |
+ -------- + -------------- + ---------------- +

我的查詢有問題,所以任何幫助都會受到影響

select priority, count(*) as priority_count, 100 * count(*) / (select count(*) from tasks where category = 'medications') as percent
from tasks 
where category = 'Medications'
group by priority

您應該將查詢作為文本放在問題中。 這使得它變得更容易。

我會把它寫成一個相關的子查詢:

SELECT t.priority,
       COUNT(t.priority) AS priority_count
       ( COUNT(t.priority) /
        (select count(*) from tasks t2 where t2.category = t.category) * 100
       ) as priority_percent
FROM tasks t
WHERE t.category = 'Medications'
GROUP BY t.priority;

您的問題是您從tasks中獲取count(*)而不是與該類別匹配的count(*)

SELECT 
priority
,COUNT(priority) AS priority_count
,COUNT(priority)/(select count(*) FROM tasks t1 WHERE t.category = t1.category) * 100 as priority_percent
FROM tasks t
WHERE category = 'Medications'
GROUP BY priority

你確定你的任務表只有這兩行嗎? 您的查詢在此上下文中是正確的,但如果您有更多行具有與“葯物”不同的類別,則結果將顯示錯誤百分比。 要解決此問題,請添加到下一個查詢

(select count(*) from tasks)

使用WHERE子句按類別過濾

(select count(*) from tasks where category='Medications')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM