SQL Server 中的动态数据透视

Dynamic pivot in SQL Server(SQL Server 中的动态数据透视)
本文介绍了SQL Server 中的动态数据透视的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对枢轴的输出有疑问.我需要它以我想要的形式来合并表.

I have problem with output from pivot. I need it in my desired form to coalesence tables.

我的结果:

us_id   Phone           Mail
1   555121313   NULL
1   NULL            LoginOne@mail.com
2   14124124    NULL
2   NULL            LoginTwo@mail.com

期望的输出:

us_id   Phone   Mail
1   555121313   LoginOne@mail.com
2   14124124    LoginTwo@mail.com

测试脚本:

create table #user (us_id int, us_login varchar(255))
INSERT INTO #user VALUES (1, 'LoginOne')
INSERT INTO #user VALUES (2, 'LoginTwo')

create table #atr_type (at_id int, at_name varchar(255))
insert into #atr_type values (1,'Phone');
insert into #atr_type values (2,'Mail')

create table #atr (atr_id int, atr_us_id int, atr_at_id int, atr_value varchar(255))
insert into #atr values(1,1,1,'555121313')
insert into #atr values(2,1,2,'LoginOne@mail.com')
insert into #atr values(3,2,1,'14124124')
insert into #atr values(4,2,2,'LoginTwo@mail.com')

我的动态枢轴代码:

DECLARE @columns NVARCHAR(MAX), @sql NVARCHAR(MAX);
SET @columns = N'';
SELECT @columns += N',' + QUOTENAME(at_name)
  FROM (  SELECT   at_name
FROM       #atr_type) AS x;

select @columns

declare @cmd varchar(max)
set @cmd = '
 SELECT us_id'+@columns+'
 FROM         #user inner join #atr on atr_us_id = us_id
inner join #atr_type on at_id = atr_at_id
PIVOT (
MIN(atr_value) FOR at_name IN
 ('

set @columns = RIGHT(@columns, LEN(@columns)-1)
set @cmd += @columns + ')
) AS PT'
exec (@cmd)

推荐答案

试试这个:

DECLARE
    @columns NVARCHAR(1000) = ''
  , @columns2 NVARCHAR(1000) = ''
  , @sql NVARCHAR(MAX)

SELECT
    @columns += N', [' + at_name + ']'
  , @columns2 += N', [' + at_name + '] = MAX([' + at_name + '])'
FROM #atr_type

SET @sql = '
 SELECT us_id' + @columns2 + '
 FROM #user inner join #atr on atr_us_id = us_id
join #atr_type on at_id = atr_at_id
PIVOT (
MIN(atr_value) FOR at_name IN
 (' + STUFF(@columns, 1,1,'') + ')
) AS PT
Group by us_id'

EXEC sp_executesql @sql

这篇关于SQL Server 中的动态数据透视的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)