日期:2014-05-17 浏览次数:20441 次
不知道这样没分开的行不
DECLARE @t1 TABLE(tid int,title varchar(100));
DECLARE @t2 TABLE(id int IDENTITY(1,1),tid int,d varchar(100),a int);
INSERT INTO @t1 SELECT 1,'选择下面正确的选项';
INSERT INTO @T2 SELECT 1,'小明',0
UNION ALL SELECT 1,'小红',1
UNION ALL SELECT 1,'小芳',0
UNION ALL SELECT 1,'小刚',1;
SELECT a.tid,a.title
,STUFF(( SELECT ','+d FROM @T2 c where c.tid=a.tid FOR XML PATH('')),1,1,'' ) AS item
,cast( (SELECT CAST(a AS varchar(10)) FROM @T2 c where c.tid=a.tid FOR XML PATH('')) AS varchar(100)) AS a
FROM @T1 a
GROUP BY a.tid,a.title;
--如果要分开,你二个表就不用id自增,可以用1,2,3,4来做,这样行转列就可以。
----------------------------
-- Author :TravyLee(物是人非事事休,欲语泪先流!)
-- Date :2012-11-22 15:52:21
-- Version:
-- Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Developer Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[tb1]
if object_id('[tb1]') is not null
drop table [tb1]
go
create table [tb1](
[题号] int,
[题目] varchar(5)
)
insert [tb1]
select 1,'问题1' union all
select 2,'问题2' union all
select 3,'问题3'
--> 测试数据:[tb2]
if object_id('[tb2]') is not null
drop table [tb2]
go
create table [tb2](
[id] int,
[题号] int,
[选项] varchar(5),
[是否正确答案] int
)
insert [tb2]
select 1,1,'选项1',0 union all
select 2,1,'选项2',1 union all
select 3,1,'选项3',1 union all
select 4,2,'选项1',0 union all
select 5,2,'选项2',1 union all
select 6,3,'选项1',0 union all
select 7,3,'选项2',1 union all
select 8,3,'选项3',0 union all
select 9,3,'选项4',0
go
with t
as(
select
a.题号,
a.题目,
b.选项,
b.是否正确答案
from
[tb1] a,
[tb2] b
where
a.题号=b.题号
)
select
题号,
题目,
选项1=max(case when 选项='选项1' then 选项 else '' end),
选项2=max(case when 选项='选项2' then 选项 else '' end),
选项3=max(case when 选项='选项3' then 选项 else '' end),
选项4=max(case when 选项='选项4' then 选项 else '' end),
是否正确答案=STUFF(
(
select
','+ltrim(是否正确答案)
from
t b
where b.题号=a.题号
for xml path('')),1,1,''