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 Programming
 return distinct key from key value

Author  Topic 

tpiazza55
Posting Yak Master

162 Posts

Posted - 2010-12-09 : 16:43:02
i have a table that has some data in key value pairs

id key value

for example:

1 orderid 100
1 payment visa

2 orderid 101
2 payment cash

3 orderid 102
3 payment cash


i need to write a query that gives me the distinct orderids from the key value pair where payment = cash for each id group


so i would want

101
102

how do i do this?


Skorch
Constraint Violating Yak Guru

300 Posts

Posted - 2010-12-09 : 17:21:55
Not sure if this will be the best solution, but it should work for your example:

declare @t table (id int, [key] varchar(20), [value] varchar(20))
insert @t
select 1, 'orderid', '100' union
select 1, 'payment', 'visa' union
select 2, 'orderid', '101' union
select 2, 'payment', 'cash' union
select 3, 'orderid', '102' union
select 3, 'payment', 'cash'

select [value] from @t a
join (select id from @t where [value] = 'cash') b
on a.id = b.id
and [value] <> 'cash'


Some days you're the dog, and some days you're the fire hydrant.
Go to Top of Page

SparkByte
Yak Posting Veteran

60 Posts

Posted - 2010-12-09 : 17:53:16
Very simular to SKorch. I had much the same thing when I noticed the new post.

But here you go anyway.



set nocount on
Declare @Orders Table
(
[id] int,
[key] VarChar(10),
[value] VarChar(10)
)

Insert into @Orders Values(1,'orderid','100')
Insert into @Orders Values(1,'Payment','Visa')
Insert into @Orders Values(2,'orderid','101')
Insert into @Orders Values(2,'Payment','cash')
Insert into @Orders Values(3,'orderid','102')
Insert into @Orders Values(3,'Payment','cash')
Insert into @Orders Values(4,'orderid','103')
Insert into @Orders Values(4,'Payment','Visa')
Insert into @Orders Values(5,'orderid','104')
Insert into @Orders Values(5,'Payment','Visa')
;

/* For Cash Orders */
Select [value] from @orders a
Join (Select id from @Orders Where [value] IN ('cash')
AND isnumeric([value]) = 0) b
On a.id = b.id
AND isnumeric([value]) = 1

/* For Credit (Non Cash) Orders */
Select [value] from @orders a
Join (Select id from @Orders Where [value] NOT IN ('cash')
AND isnumeric([value]) = 0) b
On a.id = b.id
AND isnumeric([value]) = 1




value
----------
101
102

value
----------
100
103
104




Thank You,

John Fuhrman
http://www.titangs.com
Go to Top of Page

tpiazza55
Posting Yak Master

162 Posts

Posted - 2010-12-09 : 19:09:54
thanks -- that got it
Go to Top of Page
   

- Advertisement -