我一直试图弄清楚如何解决这个问题,但没有成功。我有 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