I have an sql table looking like this:
+----+-----------+------------+ | Id | EnquiryId | PropertyId | +----+-----------+------------+ | 1 | 1 | 20 | | 2 | 1 | 25 | | 3 | 1 | 26 | | 4 | 2 | 20 | | 5 | 3 | 20 | | 6 | 4 | 20 | +----+-----------+------------+
I want to count how many enquiries propertyid 20 has on it's own, and how many that is shared with other properties
So the result should be something like this:
Number of single enguiry: 3
Number of shared enquiries: 1
It's perfectly fine if it requires two select statements :)
The attempts so far looks like this:
(select count(distinct [EnquiryId])
from [EnquiryProperty] where propertyid=20) as 'SingleEnquiry'
This gave me 4 results (I need it to be 3)
(select count([PropertyId]) FROM [EnquiryProperty] where propertyid=20 GROUP BY propertyid HAVING COUNT(*) > 1) as 'MultipleEnquiry'
And this gave me 0 results
One method is two levels of aggregation. The inner level assigns flags to each enquiry. The second uses those to get the information you want:
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;
You can do same in 2 steps (its a tad easier to understand and has no nesting):
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.