2

使用下面的代码,我得到有多少不是“Out”的项目,但它返回所有项目的百分比,而不是每个人的百分比。我知道这与计算所有 unitid 的所有日期的 count(date) 有关。有什么方法可以计算每个项目,所以它不显示总百分比?

SELECT unitid, (COUNT(date)* 100 / (SELECT COUNT(*) FROM items)) AS Percentage
FROM items
WHERE date !='Out'
GROUP BY unitid

EDIT1,澄清:假设我每种产品有 2 个,产品 a、b、c、d 和 e,每个项目中的一个是“Out”。我得到的结果是:

    unitid    Percentage
1.  a         10
2.  b         10
3.  c         10
4.  d         10
5.  e         10

我希望它显示这个:

    unitid    Percentage
1.  a         50
2.  b         50
3.  c         50
4.  d         50
5.  e         50

谢谢 :)

4

3 回答 3

2

您需要计数项目和所选项目之间的链接。

SELECT
   unitid,
   COUNT(date) * 100
      / (SELECT COUNT(*) FROM items B WHERE B.unidid = A.unitid) AS Percentage
FROM items A
WHERE date !='Out'
GROUP BY unitid
于 2012-12-28T12:21:37.190 回答
2

您查询不需要子查询,只需要条件聚合:

SELECT i.unitid, 100*sum(case when date <> 'Out' then 1 else 0 end)/count(date) as Percentage
FROM items i
GROUP BY unitid

假设 [date] 从不为 NULL,您可以更简单地表示为:

select i.unitid, 100*avg(case when date<>'out' then 1.0 else 0 end) as Percentage
from items i
group by unitid
于 2012-12-28T15:40:58.687 回答
0

让我们看看我是否理解正确。如果您有 1 个 a、2 个 b、3 个 c 和 4 个 d,每一个都是“Out”,无论是什么,您的结果集应该是:

    unitid    Percentage
1.  a         100.00
2.  b         50.00
3.  c         33.33
4.  d         25.00

为此,您可以尝试以下操作:

Select counts.unitId, 100.0 *outcounts.count/ counts.count  as Percentage
from (select unitid, count(*) as count 
        from items 
        where items.date ='Out' 
        group by unitid) as outcounts
  inner join (select unitid, count(*) as count 
              from items 
              group by unitid) as counts
    on outcounts.unitId = counts.unitId

这是一个带有设置的SQL Fiddle

于 2012-12-28T12:33:15.663 回答