SQL Query转置数据

时间:2014-02-07 02:21:17

标签: sql sql-server

我在SQL Server 2008中有以下表格:

ID  Type    Value
6   A_Left  A
6   B_Left  B
6   C_Left  C
6   D_Left  D
6   E_Left  E
6   A_Right A
6   B_Right B
6   C_Right C
6   D_Right D
6   E_Right E

我需要根据Value列对它们进行分组,如:

ID  Type    Type    Value
6   A_Left  A_Right A
6   B_Left  B_Right B
6   C_Left  C_Right C
6   D_Left  D_Right D
6   E_Left  E_Right E

这可能吗?我没有得到关于这种转置被称为google的确切术语。

2 个答案:

答案 0 :(得分:1)

使用INNER JOIN,将表连接到自身。在联接的一侧,限制为匹配_Left的那些,另一方面,限制为匹配_Right的那些。

SELECT
  l.ID,
  l.Type AS L_Type,
  r.Type AS R_Type,
  l.Value
FROM
  t l
  INNER JOIN t r ON l.ID = r.ID AND l.Value = r.Value
WHERE
  RIGHT(l.type, 4) = 'Left'
  AND RIGHT(r.type, 5) = 'Right'

以下是演示:http://sqlfiddle.com/#!6/f6590/4

或者,您可以使用LIKE而不是RIGHT()字符串函数:

SELECT
  l.ID,
  l.Type AS L_Type,
  r.Type AS R_Type,
  l.Value
FROM
  t l
  INNER JOIN t r ON l.ID = r.ID AND l.Value = r.Value
WHERE
  l.type LIKE '%_Left'
  AND r.type LIKE '%_Right'

http://sqlfiddle.com/#!6/f6590/5

答案 1 :(得分:1)

使用PATINDEX:

SELECT t1.ID, t1.Type As Type, t2.Type AS Type, t1.Value As Value 
FROM t as t1 JOIN t t2 ON t1.ID=t2.ID AND t1.Value=t2.Value
WHERE PATINDEX('%_Left',t1.Type)>0 
AND PATINDEX('%_Right',t2.Type)>0

与上述类似,但使用CTE AND LIKE(也可以使用PATINDEX):

WITH CTE AS
(
    Select ID,Type,Value FROM t WHERE Type LIKE '%_Left'
)

SELECT t1.ID,CTE.Type+ ',' + t1.Type As Type,t1.Value FROM CTE
JOIN t t1
ON t1.ID = CTE.ID AND t1.Value = CTE.Value 
WHERE  t1.Type LIKE '%_Right'