【问题标题】:Individual percentage for each item, throughput每个项目的单独百分比,吞吐量
【发布时间】:2012-12-28 11:53:42
【问题描述】:

通过以下代码,我得到了不是“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

谢谢:)

【问题讨论】:

  • 您能否展示一些示例数据来解释问题和所需的输出?

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


【解决方案1】:

您需要在计数项目和所选项目之间建立一个链接

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

【讨论】:

  • 这个答案不是最好的,因为它必须连接两个表。请参阅Gordon Linoff's answer 了解如何在单个表扫描中执行此操作。这也只会给出整数百分比(例如33)。要返回带有分数的小数百分比,例如 33.33333,请使用 * 100.0
  • 我承认这有点问答,但结果是正确的。 Gordons 查询不会在 date = 'out' 上进行过滤,因此不会产生正确的答案。
【解决方案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

【讨论】:

  • 这是最好的答案。 OP 的 selected answer 不是最好的,因为它必须执行连接,但此查询将执行一次扫描。
【解决方案3】:

让我们看看我是否理解正确。如果你有 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-03-14
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多