Question

Let's I have a inner join which results in a table as follows

WORKFLOWID  Value
1           One
1           Two
2           Three
2           Four

But what I want for this is one record to come back

ID    Value1 Value2
1     One    Two
2     Three  Four

What options do I have in SQL to change an inner join to behave as above ?

SELECT ws.workflow_id as WorkflowId, sg.unmatched_value as UnmatchedValue
FROM [geo_workflow_step] as ws 
INNER JOIN [geo_workflow] as gw on ws.workflow_id = gw.id
INNER JOIN [geo_super_group] as sg on gw.super_group_id = sg.ID
order by WorkflowId
Was it helpful?

Solution

select t1.workflowid as id,
       min(t1.value) as value1,
       max(t2.value) as value2
from the_table t1
  join the_table t2 
    on t1.workflowid = t2.workflowid
   and t1.value <> t2.value
group by t1.workflowid

This assumes that there are always exactly two rows present in the table. If this is not the case, you will indeed lookup the PIVOT operator (search for it, there are tons of questions for that on SO)

SQLFiddle: http://www.sqlfiddle.com/#!3/97e8b/2

OTHER TIPS

Try this:

WITH CTE AS
(SELECT *,RN=ROW_NUMBER() OVER(PARTITION BY WORKFLOWID ORDER BY WORKFLOWID) 
 FROM TableName)

SELECT WORKFLOWID,MAX(Value1) as Value1,MAX(Value2) as Value2
FROM
(SELECT WORKFLOWID,
       CASE WHEN RN=1 THEN Value END as Value1,
       CASE WHEN RN=2 THEN Value END as Value2
FROM CTE) T
GROUP BY WORKFLOWID

Result:

WORKFLOWID  VALUE1   VALUE2
1           One      Two
2           Three    Four

See result in SQL Fiddle.

DECLARE @t TABLE (Id int,value varchar(20))
INSERT INTO @t
VALUES (1,
        'one'),(1,
                'Two'), (2,
                         'three'),(2,
                                   'four') ;

WITH CTE AS
  ( SELECT DISTINCT t.Id,
                    t.value AS value1,
                    tt.value AS value2,
                    ROW_NUMBER()over(partition BY t.id
                                     ORDER BY t.id)AS RN
   FROM @t t
   INNER JOIN @t tt ON t.Id = tt.Id
   AND t.value <> tt.value )
SELECT ID,
       value1,
       value2
FROM CTE
WHERE rn > 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top