PhoneBill
table
Id, Number, PersonId, Bill
---------------------------
1, 123456789, 1001, 50
2, 123456789, 1001, 38
3, 123456789, 1002, 77
It's a Phone-Bill table, there are columns for phone number, the phone belonged to whom (PersonId), per-month charge (Bill).
I want to do a check if a certain phone belonged to more than 1 person. I know a way:
SELECT COUNT(PersonId)
FROM PhoneBill
WHERE Number = 'xxx'
GROUP BY PersonId
But this is low performance, since it would look for all of the PersonId
s. I just need to know if there are more than 1 person use this phone.
4条答案
按热度按时间wqnecbli1#
Can you pl check this? Here you are not grouping first for all personid's so it needs less compute. Also, I am sure that postgres allows this syntax, but I am not sure about sql-server though.
epfja78i2#
I highly doubt that the
GROUP BY
query would hve a significant performance impact, unless there were a very, very large number of rows for thatNumber
value.But you can also do this using
TOP (2) WITH TIES
, which will give you all tied results for the first twoPersonId
values.lymnna713#
Stupid I was, that's quite a simple solution.
qjp7pelc4#
You can join the table itself on same number but different PersonId, then check top 2 different ids.
Edit:
Considering Charlieface's suggestion, after some meditation, I think moving the condition
a.Number = 'xxx'
to JOIN ON clause could be better. Actually just needTOP 1
to know there are different Person own a same phone.