让我有一个内连接,产生如下表格
WORKFLOWID Value
1 One
1 Two
2 Three
2 Four
但我想要的是一条回来的记录
ID Value1 Value2
1 One Two
2 Three Four
我在SQL中有哪些选项可以将内部联接更改为上述行为?
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
答案 0 :(得分:4)
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
这假设表中总是存在两行。如果不是这种情况,你确实会查找PIVOT
运算符(搜索它,在SO上有很多问题)
SQLFiddle:http://www.sqlfiddle.com/#!3/97e8b/2
答案 1 :(得分:0)
试试这个:
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
结果:
WORKFLOWID VALUE1 VALUE2
1 One Two
2 Three Four
请参阅SQL Fiddle中的结果。
答案 2 :(得分:0)
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