SQL结果列值作为结果

时间:2014-04-25 17:48:21

标签: sql-server sql-server-2008

我希望从所提供的样本表中获得所期望的结果。

我一直在努力创建SQL来处理这个问题:

CREATE TABLE a (account nvarchar(10), accountname nvarchar(10));
CREATE TABLE b (bid int, bdesc nvarchar(10));
CREATE TABLE C (cid int, bid int, caccount nvarchar(10));

INSERT INTO a VALUES ('a1','a1val');
INSERT INTO a VALUES ('b1','b1val');
INSERT INTO a VALUES ('c1','c1val');
INSERT INTO a VALUES ('d1','d1val');

INSERT INTO b VALUES (1,'val1');
INSERT INTO b VALUES (2,'val2');
INSERT INTO b VALUES (3,'val3');

INSERT INTO c VALUES (1,1,'a1');
INSERT INTO c VALUES (2,1,'b1');
INSERT INTO c VALUES (3,2,'a1');
INSERT INTO c VALUES (4,3,'c1');

--Desired results
--accountname  val1  val2  val3
--a1val        x     x  
--b1val        x
--c1val                    x
--d1val

select * from a
select * from b
select * from c 

drop table a, b, c

1 个答案:

答案 0 :(得分:0)

此解决方案适用于bdesc中的任意数量的不同值。

declare @dynamicSQL varchar(max) = ''
declare @columnList varchar(max) = ''
declare @unique table ([bdesc] varchar(10) )
insert into @unique
select distinct [bdesc] from b 
select @columnList = @columnList + '[' + bdesc + '],'  from @unique
set @columnList = SUBSTRING(@columnList, 0, LEN(@columnList))
set @dynamicSQL = '' +
'select *
from
(
select accountname, bdesc
from a as a
left join c as c
on a.account = c.caccount
left join b as b
on c.bid = b.bid
) as src
pivot(
max(bdesc)
for bdesc in (' + @columnList + ')' + '
) as pvt'
exec(@dynamicSQL)