2014-04-25 146 views
-1

我想從所提供的示例表中獲得所需結果中顯示的內容。SQL結果列值作爲結果

我一直在努力與創建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

可能重複(http://stackoverflow.com/questions/1768586/sql-convert-rows-to-columns) –

回答

0

該解決方案適用於任何數量的BDESC不同值的工作。的[SQL轉換行列]

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) 
+0

這應該讓我足夠的前進。謝謝。 – user3301576

+0

儘管val1,2和3是一個大問題,但它們都是硬編碼的。在這個例子中我永遠不會知道表b的內容。 – user3301576

+0

@ user3301576 - 哦...現在你提到它。 –