SQL中的行的列 [英] Columns to Row in SQL

查看:58
本文介绍了SQL中的行的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的朋友们,我需要你的帮助解决这个问题。

我的数据格式为

名称价值

John 100

John 1000

John 2000

史密斯100

史密斯300



我需要输出

John 100,1000,2000

史密斯100,300



我可以使用这个案例,但现在计数可以是n号。

所以我需要动态解决方案。

请指导。

Dear Friends, I need your help to sort out this issue.
I have a data in the format as
Name Value
John 100
John 1000
John 2000
Smith 100
Smith 300

I need to output as
John 100, 1000, 2000
Smith 100, 300

I can get this using case when but now the count can be n number.
So i need to dynamic solution.
Please guide.

推荐答案

很多例子是此处 [ ^ ]



其中两个:

在SQL中使用Pivot的简单方法查询 [ ^ ]

在SQL Server中一起使用PIVOT和JOIN [ ^ ]
Tons of example is here[^]

Two of them:
Simple Way To Use Pivot In SQL Query[^]
Using PIVOT and JOIN Together in SQL Server[^]


检查此查询希望这对您有所帮助。



Check this query hope this will help you.

--Create sample table
create table samplePivot(
Name varchar(50),
itemValue int
)

--Insert sample record
insert into samplePivot(Name,itemValue) values('John',100)
insert into samplePivot(Name,itemValue) values('John',1000)
insert into samplePivot(Name,itemValue) values('John',2000)
insert into samplePivot(Name,itemValue) values('Smith',100)
insert into samplePivot(Name,itemValue) values('Smith',300)

--Pivot query for your result

DECLARE @MyColumns AS NVARCHAR(MAX),
    @SQLquery  AS NVARCHAR(MAX)
-- here first we get all the ItemName which should be display in Columns we use this in our necxt pivot query
select @MyColumns = STUFF((SELECT ',' + QUOTENAME(itemValue) 
                    FROM samplePivot
                    GROUP BY itemValue
                    ORDER BY itemValue
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
        
        select @MyColumns
        
-- here we use the above all Item name to disoplay its price as column and row display
set @SQLquery = N'SELECT Name,' + @MyColumns + N' from 
             (
                 SELECT 
       Name, 
        itemValue  as itemValue
    FROM samplePivot
            ) x
            pivot 
            (
                 sum(itemValue)
                for itemValue in (' + @MyColumns + N')
            ) p '
exec sp_executesql @SQLquery;


试试这个动态数据透视表:



http://sqlhints.com / 2014/03/18 / dynamic-pivot-in-sql-server / [ ^ ]



最好的办法就是自己尝试:)
Try this Dynamic Pivot :

http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/[^]

The Best way is try yourself :)


这篇关于SQL中的行的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆