Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Administration
 Group by data that is across two separate columns

Author  Topic 

SergioM
Posting Yak Master

170 Posts

Posted - 2014-05-20 : 16:07:30
I want to find all duplicate occurrences of UPCs. For me, UPCs can be in one table or another, so I have to do an UNION ALL. The problem is that once I do that, I can no longer effectively count the UPCs. What I want is to list the UPCs and the amount of times that they occur. But I get an error message. This is my sample data. I feel like I'm close to it, but it's not working.


Declare @Temp1 Table(
Sku nvarchar(100)
,UPC nvarchar(100)
)
Insert into @Temp1 Values('ABCD','61345')
Insert into @Temp1 Values('EBCD','72345')
Insert into @Temp1 Values('FBCD','52345')
Insert into @Temp1 Values('SBCD','22345')

Declare @Temp2 Table(
Sku nvarchar(100)
,UPC nvarchar(100)
)
Insert into @Temp2 Values('ASDF','61345')
Insert into @Temp2 Values('BSDF','52343')
Insert into @Temp2 Values('CSDF','52345')
Insert into @Temp2 Values('DSDF','72343')

Select UPC
From @Temp1
UNION ALL
Select UPC
From @Temp2
GROUP BY (UPC)
HAVING COUNT(UPC)>1


-Sergio
I use Microsoft SQL 2008

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2014-05-20 : 16:17:48
select UPC, count(*)
from (Select UPC From @Temp1 ALL Select UPC From @Temp2) t
GROUP BY (UPC)
HAVING COUNT(UPC)>1

Tara Kizer
SQL Server MVP since 2007
http://weblogs.sqlteam.com/tarad/
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2014-05-20 : 16:18:51
Add union before the ALL. For some reason, "union" in my post is causing it not to be posted.

Tara Kizer
SQL Server MVP since 2007
http://weblogs.sqlteam.com/tarad/
Go to Top of Page

SergioM
Posting Yak Master

170 Posts

Posted - 2014-05-21 : 11:45:52
Thanks!

-Sergio
I use Microsoft SQL 2008
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2014-05-21 : 12:20:31


Tara Kizer
SQL Server MVP since 2007
http://weblogs.sqlteam.com/tarad/
Go to Top of Page
   

- Advertisement -