将sql表行显示为列

时间:2013-10-24 12:02:06

标签: sql-server pivot

我有一个名为NewDemo的表。

ID  Name     Condition  Value
--  ----     ---------  -----
1   Book     Amount     90/-
2   Pencil   Amount      5/-
3   Eraser   Amount     7/-
1   Book     Quantity   900
2   Pencil   Quantity   280
3   Eraser   Quantity   200

但我想要显示如下

ID    Name     Amount     Quantity
--    ----     ------     --------
1     Book     90/-       900
2     Pencil   5/-        280
3     Eraser   7/-        200

给我一​​些解决方案...... / 谢谢大家

4 个答案:

答案 0 :(得分:2)

在sql-server中::试试这个

select * from [dbo].[2]
pivot
(
max(value)
for condition in([amount],[quantity]) 
)as piv order by id

答案 1 :(得分:0)

你可以这样做。

SELECT A.ID, A.Name, A.Value AS 'Amount', B.Value AS 'Quantity'
FROM (SELECT * FROM NewDemo WHERE Condition = 'Amount') AS A
    JOIN (SELECT * FROM NewDemo WHERE Condition = 'Quantity') AS B
    ON A.ID = B.ID

答案 2 :(得分:0)

SELECT a.ID, a.Name, a.Value as Amount, b.Value as Quantity FROM 
(SELECT ID, Name, Value FROM NewDemo WHERE Condition = 'Amount') a 
LEFT JOIN (SELECT ID, Name, Value FROM NewDemo WHERE Condition = 'Quantity') b 
on a.ID = b.ID

答案 3 :(得分:0)

嗨,我认为这会对你有所帮助

SELECT     ID, Name, MAX(DISTINCT CASE WHEN Condition = 'Amount' THEN Value END) AS   Amount, MAX(DISTINCT CASE WHEN Condition = 'Quantity' THEN Value END) 
           AS Quantity
FROM       dbo.TESTTABLE
GROUP BY   ID, Name