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.
| Author |
Topic |
|
swirls
Starting Member
5 Posts |
Posted - 2010-06-22 : 01:43:43
|
| Am wondering if anyone can help me here.What I'm trying to do is get the query to return the associated row value where a particular FieldID exists.For example, I have the following Table A with data as per below:OrderID FieldID FieldValue------- ------- ----------11111 123 Install11111 234 Version 111111 NAME John Smith11111 ADD Station Street22222 123 Pickup22222 234 Version 233333 NAME Jane DoeI want the query to return values in the OrderID and FieldValue column where FieldID = 'NAME', and if FieldID = 'NAME' doesn't exist, return a blank. The result of the query should be the following:OrderID FieldValue------- ----------11111 John Smith22222 33333 Jane DoeI have built the following query:SELECT A.OrderID,CASE WHEN A.FieldID = 'QNAME' THEN A.FieldValue ELSE '' ENDFROM dbo.AHowever, the above will return the following instead:OrderID FieldValue------- ----------11111 11111 11111 John Smith11111 22222 22222 33333 Jane DoeSeems to be returning everything in the table except substituting the FieldValue with blanks when NAME is not found. |
|
|
webfred
Master Smack Fu Yak Hacker
8781 Posts |
Posted - 2010-06-22 : 02:10:44
|
[code]-- making test datadeclare @test table (OrderID int, FieldID varchar(255), FieldValue varchar(255))insert @testselect 11111, '123', 'Install' union allselect 11111, '234', 'Version 1' union allselect 11111, 'NAME', 'John Smith' union allselect 11111, 'ADD', 'Station Street' union allselect 22222, '123', 'Pickup' union allselect 22222, '234', 'Version 2' union allselect 33333, 'NAME', 'Jane Doe'-- the solutionselect OrderID, FieldValue from @testwhere FieldID = 'NAME'unionselect OrderID, '' from @test t1where not exists(select * from @test t2 where t2.OrderID=t1.OrderID and t2.FieldID='NAME')[/code] No, you're never too old to Yak'n'Roll if you're too young to die. |
 |
|
|
Llewellyn
Starting Member
13 Posts |
Posted - 2010-06-23 : 10:44:01
|
| select distinct OrderID, case when FieldID = 'NAME' then FieldValue else '' endfrom TableAwhere FieldID = 'NAME' or OrderID not in (SELECT OrderID FROM TableA where FieldID = 'NAME') |
 |
|
|
|
|
|
|
|