计算发生的频率

时间:2014-11-19 21:09:46

标签: sql-server sql-server-2012

Company_ID  Priority
1               1
1              10
1               1
1              10
2               1
3               1
3               1
4               1
8               1

我的数据库中有上表(类似),我需要计算优先级= 1的公司ID的发生频率。

即。预期结果,

Frequency   NoOfCompanies
1               3
2               2

3家公司优先1次记录3次。 2家公司优先1次记录2次。

我有我试过的查询,并不想与我拥有的所有联接混淆。以上是简化版本,因此易于理解。

3 个答案:

答案 0 :(得分:1)

您需要将数据汇总两次:

SELECT Frequency, COUNT(*) NoOfCompanies
FROM (
  SELECT COUNT(*) Frequency
  FROM Companies
  WHERE Priority = 1
  GROUP BY Company_ID
) Frequencies
GROUP BY Frequency
ORDER BY Frequency

SQLFiddle here

答案 1 :(得分:1)

让我们制作一些测试数据:

DECLARE @MyTable TABLE
(
    Company_ID  int,
    Priority    int
)

INSERT INTO @MyTable
( Company_ID, Priority )
VALUES
(1, 1),
(1, 10),
(1, 1),
(1, 10),
(2, 1),
(3, 1),
(3, 1),
(4, 1),
(8, 1);

现在让我们看看每家公司的频率:

SELECT Company_ID, Priority, COUNT(*) AS Frequency FROM @MyTable
GROUP BY Company_ID, Priority

输出:

Company_ID  Priority    Frequency
1   1   2
2   1   1
3   1   2
4   1   1
8   1   1
1   10  2

现在让我们看看每个频率的计数:

SELECT Frequency, COUNT(d.Company_ID) NoOfCompanies FROM
(
SELECT Company_ID, Priority, COUNT(*) AS Frequency FROM @MyTable
GROUP BY Company_ID, Priority
) d
GROUP BY Frequency

输出:

Frequency   NoOfCompanies
1   3
2   3

答案 2 :(得分:0)

这应该在DB2中执行:

使用topPriority  AS(SELECT Company_ID FROM table WHERE priority = 1)

SELECT Company_ID,COUNT(*)FROM topPriority GROUP BY Company_ID

编辑:有人更快......