计算SQL Server中的共享列值

时间:2014-01-29 08:38:18

标签: sql sql-server

我有一张看起来像这样的表:

--------------------------
| Client       | Unit    |
--------------------------
| Acme         | Unit-2  |
| Acme         | Unit-2  |
| Acme         | Unit-9  |
| Foo          | Unit-5  |
| Foo          | Unit-8  |
| Acme         | Unit-9  |
| Foo          | Unit-9  |
| Acme         | Unit-1  |
| Foo          | Unit-2  |
| Foo          | Unit-9  |
--------------------------

正如您所看到的,客户Acme已与Unit-9相关联两次。客户Foo也与Unit-9相关联。

Unit-2也是如此。客户Acme与之关联两次,但Foo与之关联一次。

我需要的是一个查询,显示共享的单位和次数。

所以在这种情况下我需要的结果是:

Unit-9 = 2 times shared
Unit-2 = 1 time sahred

对于Unit-9AcmeFoo都会被Unit-9链接两次,因此它应显示为2 times shared

对于Unit-2,只有AcmeUnit-2相关联,而FooUnit-2相关联一次。因此,在这种情况下,他们会共享{{1}}次。


我根本不知道如何为此创建查询。任何人都知道如何做到这一点?

2 个答案:

答案 0 :(得分:2)

我认为你正在寻找这个:

WITH shares 
     AS (SELECT client, 
                unit, 
                Count(*) AS no 
         FROM   yourtable 
         GROUP  BY client, 
                   unit) 
SELECT unit, 
       Min(no) AS times_shared 
FROM   shares 
GROUP  BY unit 

答案 1 :(得分:-1)

此查询是您所需要的,请注意以下其他不正确的选项

这是SQL SERVER的 CORRECT 查询

 SELECT Unit, COUNT(DISTINCT Client) FROM ClientUnitTable GROUP BY Unit

给你

 Unit-1 = 1
 Unit-2 = 2
 Unit-5 = 1
 Unit-8 = 1
 Unit-9 = 2

请注意,这些 INCORRECT 查询会产生错误的结果

 SELECT Unit, COUNT(Client) FROM ClientUnitTable GROUP BY Unit
 SELECT Unit, COUNT(*) FROM ClientUnitTable GROUP BY Unit
 SELECT Unit, COUNT(*) FROM ClientUnitTable GROUP BY Client (Doesn't Even Process)