October 23, 2013 at 2:26 pm
Something I thought would be so simple has me scratching my head. How do we return only those table rows where three of the columns match? For example on the attached doc we only want to return the third and fourth rows where the partnumber, serial no, and uid match. Any help will be greatly appreciated.
October 23, 2013 at 2:35 pm
Please post ddl and consumable data in the future. The query itself is pretty trivial but setting up the problem from a spreadsheet is painful.
Here is one way to do this.
create table #Something
(
ID int,
PartNum varchar(20),
SerialNum int,
UserID int
)
insert #Something
select 30448, '019-018-001', 376, 169132 union all
select 35739, '019-018-001', 232, 185155 union all
select 37658, '019-018-001', 232, 185155 union all
select 1283, '019-018-001', 242, 118818 union all
select 2022, '019-018-001', 240, 118453 union all
select 2023, '019-018-001', 249, 118452 union all
select 2030, '019-018-001', 187, 118454;
with matches as
(
select COUNT(*) as MyCount, PartNum, SerialNum, UserID
from #Something
group by PartNum, SerialNum, UserID
having COUNT(*) > 1
)
select s.*
from #Something s
join matches m on m.PartNum = s.PartNum and s.SerialNum = m.SerialNum and s.UserID = m.UserID;
drop table #Something
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
October 24, 2013 at 9:05 am
That worked great. Much appreciated.
October 24, 2013 at 9:13 am
You are welcome. Glad that worked for you.
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply