如果你只有几列,您可以使用一个静态的支点:
create table #temp
(
name varchar(50),
date datetime,
yesno bit
)
insert into #temp values('John', '01/01/2012', 1)
insert into #temp values('Mary', '01/01/2012', 1)
insert into #temp values('James', '01/01/2012', 1)
insert into #temp values('John', '01/02/2012', 0)
insert into #temp values('Mary', '01/02/2012', 0)
insert into #temp values('James', '01/02/2012', 0)
insert into #temp values('John', '01/03/2012', 1)
insert into #temp values('Mary', '01/03/2012', 0)
insert into #temp values('James', '01/03/2012', 1)
select name, [01/01/2012], [01/02/2012], [01/03/2012]
from
(
select name, date, cast(yesno as tinyint) as yesno
from #temp
) x
pivot
(
max(yesno)
for date in ([01/01/2012], [01/02/2012], [01/03/2012])
) p
drop table #temp
但它听起来像你想为这个动态的支点。要做到这一点,你必须首先得到列的列表转动,然后运行查询:
create table test
(
name varchar(50),
date datetime,
yesno bit
)
insert into test values('John', '01/01/2012', 1)
insert into test values('Mary', '01/01/2012', 1)
insert into test values('James', '01/01/2012', 1)
insert into test values('John', '01/02/2012', 0)
insert into test values('Mary', '01/02/2012', 0)
insert into test values('James', '01/02/2012', 0)
insert into test values('John', '01/03/2012', 1)
insert into test values('Mary', '01/03/2012', 0)
insert into test values('James', '01/03/2012', 1)
DECLARE @cols AS VARCHAR(MAX),
@query AS VARCHAR(MAX);
SELECT @cols = STUFF((SELECT DISTINCT TOP 100 PERCENT
'],[' + convert(varchar(10), t2.date, 101)
FROM test AS t2
ORDER BY '],[' + convert(varchar(10), t2.date, 101)
FOR XML PATH('')
), 1, 2, '') + ']'
set @query = 'select name, ' + @cols + '
from
(
select name, date, cast(yesno as tinyint) as yesno
from test
) x
pivot
(
max(yesno)
for date in (' + @cols + ')
) p'
execute(@query)
这里是动态的枢轴一些有用的链接:
Pivots with Dynamic Columns in SQL Server
Using SQL Server 2005/2008 Pivot on Unknown Number of Columns (Dynamic Pivot)
有对于动态支点,SO是很多问题/答案。
谢谢你Bluefeet的收拾,我是小白在这里,所以不能发表图片: D – AlwaysLearning 2012-04-03 20:53:52