计算不同的和非不同的值

时间:2017-10-19 10:14:06

标签: sql sql-server

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

+----+-----------+------------+
| Id | EnquiryId | PropertyId |
+----+-----------+------------+
|  1 |         1 |        20  |
|  2 |         1 |        25  |
|  3 |         1 |        26  |
|  4 |         2 |        20  |
|  5 |         3 |        20  |
|  6 |         4 |        20  |
+----+-----------+------------+

我想计算一下propertyid 20有多少查询,以及与其他属性共享多少查询

所以结果应该是这样的:

单个工程数:3

共享查询次数:1

如果需要两个选择语句,那就完全没问题了:)

到目前为止的尝试看起来像这样:

(select count(distinct [EnquiryId]) 
from [EnquiryProperty] where propertyid=20) as 'SingleEnquiry'

这给了我4个结果(我需要它为3)

(select count([PropertyId]) FROM [EnquiryProperty] where propertyid=20 GROUP BY propertyid HAVING COUNT(*) > 1) as 'MultipleEnquiry'

这给了我0个结果

2 个答案:

答案 0 :(得分:5)

一种方法是两级聚合。内层为每个查询分配标志。第二个用它来获取你想要的信息:

select sum(is_20 * (1 - is_not_20)) as single_enquiry,
       sum(is_20 * is_not_20) as shared_enquiry
from (select enquiryid,
             max(case when propertyid = 20 then 1 else 0 end) as is_20,
             max(case when propertyid <> 20 then 1 else 0 end) as is_not_20
      from t
      group by enquiryid
     ) e;

答案 1 :(得分:1)

你可以分两步完成(它有点容易理解,没有嵌套):

select count(PropertyId) AS Single20s
from WhateverTableIsCalled
group by EnguryId
having count(PropertyId) = 1

select count(PropertyId) AS Shared20s
from WhateverTableIsCalled
group by EnguryId
having count(PropertyId) > 1