每个项目的单独百分比,吞吐量

时间:2012-12-28 11:53:43

标签: sql sql-server sql-server-2012

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

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

谢谢:)

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

让我们看看我是否正确理解了这一点。如果你有一个a,两个b,三个c和四个s,其中一个是“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
相关问题