我有一个包含这样数据的表:
Id Value
-------------------------
01 Id01-Value1
01 Id01-Value2
02 Id02-Value1
02 Id02-Value2
03 Id03-Value1
我想要的是
Id Value1 Value2
--------------------------------------
01 Id01-Value1 Id01-Value2
02 Id02-Value1 Id02-Value2
03 Id03-Value1
我试过sql PIVOT
,但我认为不是这类问题。
答案 0 :(得分:1)
我认为您可以使用min()
和max()
:
select id, min(value) as value1,
(case when min(value) <> max(value) then max(value) end) as value2
from t
group by id;
答案 1 :(得分:0)
试试这个答案,
SELECT ID
,MAX(CASE WHEN RN=1 THEN Value ELSE '' END)Value1
,MAX(CASE WHEN RN=2 THEN Value ELSE '' END)Value2
FROM(
SELECT ID,Value
,ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Value)RN
FROM Your_Table
)D
GROUP BY ID
ORDER BY ID
答案 2 :(得分:0)
恰恰相反,PIVOT
正是你所需要的 - 如果你能忍受它的语法!它相对灵活,但也很笨重。
SELECT
id
,[1] AS Value1
,[2] AS Value2
FROM
(
SELECT
id
,value
,ROW_NUMBER() OVER (PARTITION BY id ORDER BY value ASC) AS column_number
FROM
YOUR_TABLE_NAME
) AS src
PIVOT
(
MAX(value)
FOR column_number IN ([1],[2])
) AS pvt
ORDER BY
id
这将按字母顺序对value
列中的行进行排序,并按顺序相应地分配列号(但您可以包含不同的逻辑,例如,将值列在值的右侧,或根据值本身命名列,而不是对它们进行编号)。对于没有值的任何列,将返回NULL值。