Avatar of James Elliott
James Elliott
Flag for United Kingdom of Great Britain and Northern Ireland asked on

SQL Query - Specify which record to join to

Hi All,

I have a table of unique codes which has a one to many relationship with a table of statuses against these codes.

Most of the time, one code has one status, but it is possible to have two statuses for one code. When there are two statuses, I want to join to the status that does not start 'xxx'.

Microsoft SQL Server 2005Microsoft SQL Server 2008Microsoft SQL Server

Avatar of undefined
Last Comment
James Elliott

8/22/2022 - Mon
Guy Hengel [angelIII / a3]

can you show some data samples? maybe something to play with on sqlfiddle?
I have some ideas, but without having concrete data (and respective required output) it will rather be guesswork
just a couple of records
Phillip Burton

How about this (This assumes a "dbo.status" table with values "Status" and "Code":

with MyStatus1 as (
select *, row_number() over(partition by code order by case substring(Status,1,3) when 'xxx' then 1 else 0 end, status) as MyRow
from dbo.status),
MyStatus2 as
(Select * from MyStatus1 where MyRow = 1)
select *
from MyStatus2

Open in new window

James Elliott

Ok, sorry for the vague question.

I have the following SQL which gives me a list of codes with status, in which there are duplicates. Basically, where there are two entries, I want to select the entry that does not start "Closed".


	CASE WHEN d.Category_1 = 'CLOSED' AND a.Eligible = 1 THEN 'Closed - Accepted'
		 WHEN d.category_1 = 'CLOSED' AND a.Eligible = 0 THEN 'Closed - Rejected'
		 ELSE d.category_1
	END as status	
	tblRequestLines a
	tblStatusLines b
ON b.Request_Line_ID = a.ID

	tblStatuses c
ON b.Status_ID = c.ID

	tblStatusCategoryMap d
ON d.Status_ID = c.ID


Open in new window

Your help has saved me hundreds of hours of internet surfing.
Phillip Burton

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Guy Hengel [angelIII / a3]

along the same lines :)
James Elliott

Thanks both. I went with Guy's solution in the end as it returned the correct number of records.