用光标+联合+枢轴查询?

Posted

技术标签:

【中文标题】用光标+联合+枢轴查询?【英文标题】:Query with Cursors+union+pivot? 【发布时间】:2012-10-01 15:39:37 【问题描述】:

我一直试图弄清楚如何解决这个问题,但没有成功。 我有 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,但不确定这是最好的解决方案 + 我不知道如何通过循环进行并集...

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

【问题讨论】:

请添加一些示例数据并告诉我们您使用的是什么 RDBMS? 【参考方案1】:

看起来您正在使用 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

【讨论】:

您好,感谢您的帮助。我在原始帖子中添加了更多详细信息。我希望它可以帮助你帮助我:) @user649904 请查看我的编辑,看来我的查询会起作用。我已经为这两个查询添加了演示。 @user649904 如果此答案有帮助,请务必通过复选标记将其标记为已接受。它会让未来的访问者知道这个问题已经解决。 对不起,这是我第一次来这里。完成了。再次感谢!

以上是关于用光标+联合+枢轴查询?的主要内容,如果未能解决你的问题,请参考以下文章

使用光标在QTreeWidgetItem中选择Text

如何显示图标可以用光标悬停

如何在 Android 中使用光标数据创建列表数组

性能下降返回光标与联合所有

我想删除从光标获取的数据而不使用更新

centos7.6开机自启一直设置不成功