3

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

13
  • 4
    What have you tried? Show us your current attempts. Commented Oct 19, 2017 at 10:16
  • stackoverflow.com/questions/13146304/… @marcus-ohlsson Commented Oct 19, 2017 at 10:17
  • Ahem : stackoverflow.com/questions/1521605/… Commented Oct 19, 2017 at 10:17
  • which database? Commented Oct 19, 2017 at 10:18
  • My attemts so far looks like this: ,(select count(distinct [EnquiryId]) from [EnquiryProperty] where propertyid=325) as 'SingleEnquiry' ,(select count([PropertyId]) FROM [EnquiryProperty] where propertyid=325 GROUP BY propertyid HAVING COUNT(*) > 1) as 'MultipleEnquiry' Commented Oct 19, 2017 at 10:19

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you verry much @SriniV, this works like a sharm :)
I like the idea with flagging 1st then aggregating the flags. Gonna keep that one in memory :)
@MarcusOhlsson, it was actually gordonlinoff to be thanked
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.