从不同的行中选择字段

时间:2014-06-26 13:53:59

标签: sql-server

我有下表Test

id value type 
1   100  prime
1   200  13 month 
2   120  prime
2   300  13 month 

如何获得以下结果

id valuePrime typePrime valueMonth typeMonth
1   100        prime      200      13 month
2   120        prime      300      13 month

3 个答案:

答案 0 :(得分:0)

修改架构:

id  parentid  value  type
---------------------------
1   null      100    prime
2   1         200    13 month 
3   null      120    prime
4   3         300    13 month 

并像这样查询:

SELECT a.id, a.value AS valuePrime, a.type AS typePrime, b.value AS valueMonth, b.type AS typeMonth
FROM Test AS a
INNER JOIN Test AS b
ON a.id=b.parentid

答案 1 :(得分:0)

在此基础上,您可以使用类型prime来分割数据:

select id, value as ValPrime, 'prime' as TypePrime from tbl where type = 'prime'

然后选择:

select id, value as ValMonth, type as TypeMonth from tbl where type != 'prime'

然后加入他们 但这是解决方法,这真的不太好:))

答案 2 :(得分:0)

这可能对您有用,但请注意,只有在只有2个记录具有与您上面显示的相同ID的情况下才能使用。我仍然会建议更改架构。以下查询可能对您有所帮助暂时。

SELECT  q1.id, q1.value AS valueprime, q1.type AS typeprime,q2.value 
as valueMonth,q2.type   as typeMonth
FROM  Test  AS q1 INNER JOIN Test AS q2 ON q1.id = q2.id AND q1.value<> q2.value