用Cursors + union + pivot查询?

时间:2012-10-01 15:39:37

标签: sql cursor pivot union

我一直想弄清楚如何解决这个问题,但没有成功。 我有2张桌子:

1)的问题

ID (pk)
QUES
ORD

2)回答

ID (pk)
QUES_ID (fk)
SURV_ID (fk)
ANSW

现在我需要创建一个视图,其中的问题是列名称,对于每个SURV_ID,如果ANSWERS中没有条目,则视图中有一行回答为NULL,如果有条目,则回答ANSW。 不确定是否可以使用JOIN进行此操作。

我正在考虑使用CURSOR,然后执行结果表的UNION,然后使用PIVOT,但不确定它是最好的解决方案+我不知道如何通过循环进行联合... < / p>

DECLARE @survID int
DECLARE db_cursor CURSOR FOR
SELECT DISTINCT SURV_ID FROM ANSWERS ORDER BY SURV_ID
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @survID

WHILE @@FETCH_STATUS = 0
BEGIN
SELECT QUES
,ANSW , SURV_ID
FROM QUESTIONS a
left outer JOIN ANSWERS b ON a.ID = b.QUES_ID
WHERE ( SURV_ID = @survID OR SURV_ID IS NULL)
FETCH NEXT FROM db_cursor INTO @survID
END
CLOSE db_cursor
DEALLOCATE db_cursor

...

更新:我面临的问题有点复杂,因为并非所有问题都有答案(在这种情况下我很乐意显示NULL),并且答案按SURV_ID分组

CREATE TABLE [QUESTIONS] (
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [QUES] [varchar](250) NOT NULL,
    [ORD] [int] NOT NULL,
CONSTRAINT [PK_QUESTIONS] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

INSERT INTO [QUESTIONS] values ('First Question', 1)
INSERT INTO [QUESTIONS] values ('Second Question', 2)

GO

CREATE TABLE [ANSWERS] (
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [SURV_ID] [int] NOT NULL,
    [QUES_ID] [int] NOT NULL,
    [ANSW] [varchar](500) NOT NULL,
CONSTRAINT [PK_ANSWERS] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

ALTER TABLE [ANSWERS]  WITH CHECK ADD  CONSTRAINT [FK_ANSWERS_QUESTIONS] FOREIGN KEY([QUES_ID])
REFERENCES [QUESTIONS] ([ID])
GO

ALTER TABLE [ANSWERS]   CHECK CONSTRAINT [FK_ANSWERS_QUESTIONS]
GO


INSERT INTO [ANSWERS] ([SURV_ID],[QUES_ID],[ANSW]) VALUES (1,1,'Y')
INSERT INTO [ANSWERS] ([SURV_ID],[QUES_ID],[ANSW]) VALUES (1,2,'N')
INSERT INTO [ANSWERS] ([SURV_ID],[QUES_ID],[ANSW]) VALUES (2,1,'N')
INSERT INTO [ANSWERS] ([SURV_ID],[QUES_ID],[ANSW]) VALUES (3,2,'Y')
INSERT INTO [ANSWERS] ([SURV_ID],[QUES_ID],[ANSW]) VALUES (4,1,'Y')
INSERT INTO [ANSWERS] ([SURV_ID],[QUES_ID],[ANSW]) VALUES (4,2,'Y')
GO

我想得到的是像

[SURV_ID]          [First Question]          [Second Question]  
1                  Y                         N  
2                  N                         null  
3                  null                      Y  
4                  Y                         Y

1 个答案:

答案 0 :(得分:2)

看起来您正在使用SQL-Server,因此以下内容应该可行。如果您知道要转换的项目数,则可以对值进行硬编码:

select *
from
(
  select a.surv_id,
    a.answ,
    q.ques
  from QUESTIONS q
  left join ANSWERS a
    on q.ID = a.QUES_ID
) x
pivot
(
  max(answ)
  for ques in ([First Question], [Second Question])
) p

请参阅SQL Fiddle With Demo

如果您不知道列数,则可以使用动态sql:

DECLARE @query  AS NVARCHAR(MAX),
    @colsPivot as  NVARCHAR(MAX)

select @colsPivot = STUFF((SELECT distinct  ',' 
                      + quotename(ques)
                    from QUESTIONS 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query 
  = 'select *
     from 
     (
        select a.surv_id,
          a.answ,
          q.ques
        from QUESTIONS q
        left join ANSWERS a
          on q.ID = a.QUES_ID
      ) x
      pivot
      (
        max(answ) 
        for ques in ('+ @colspivot +')
      ) p'

exec(@query)

请参阅SQL Fiddle with Demo