Click here to Skip to main content
15,889,992 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have the following table. How can I find if a Parent has multiple items.

For Eg: Parent 1 has items ABC and BBC, So the query should display '(Multiple)' instead of showing Item names. Parent 5 has only single item, It should show the Item name.

Price      |    Item    |  Parent
-----------|------------|-------------
20         |   ABC      |   1
10         |   BBC      |   1
5          |   CBC      |   5
21         |   DDB      |   6
17         |   BDD      |   6
31         |   DBB      |   6


What I have tried:

I have created the following query which doesn't seems to be working.

SQL
SELECT CASE WHEN COUNT(*) > 1 THEN '(Multiple)' ELSE Item END FROM 
(SELECT COUNT(*), Item FROM Table WHERE Parent = @parent 
GROUP BY Item) Table GROUP BY Item
Posted
Updated 7-Jul-18 0:07am

1 solution

I think this will do it:
SQL
SELECT   parent, 
         count(*) AS [Count] 
FROM     dbo.[mytable] 
GROUP BY parent 
HAVING   COUNT(Parent) > 1


UPDATE ================================

SQL
;WITH cte AS
(
SELECT   parent, 
         SUM(1) AS quantity
FROM     dbo.[parents] 
GROUP BY parent 
)
SELECT a.parent,
       MAX(CASE WHEN b.quantity=1 THEN a.item ELSE 'Multiple' END) AS Item
FROM   dbo.[parents] AS a
FULL JOIN cte AS b ON b.parent = a.parent
GROUP BY a.parent
ORDER BY a.parent
 
Share this answer
 
v4
Comments
Yesudass Moses 7-Jul-18 6:25am    
Still, How will I get the item name or 'Multiple'
#realJSOP 7-Jul-18 7:21am    
For f*ck sake - be a programmer. I updated my answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900