【发布时间】:2015-02-08 07:42:09
【问题描述】:
我有三张桌子。测试表 (AdminTest)、属于用户的测试表 (UserTest) 和属于每个用户测试的问题表 (UserTestQuestion):
管理测试
CREATE TABLE [dbo].[AdminTest] (
[AdminTestId] INT IDENTITY (1, 1) NOT NULL,
[Title] NVARCHAR (100) NOT NULL
CONSTRAINT [PK_AdminTest] PRIMARY KEY CLUSTERED ([AdminTestId] ASC));
用户测试
CREATE TABLE [dbo].[UserTest] (
[UserTestId] INT IDENTITY (1, 1) NOT NULL,
[AdminTestId] INT NOT NULL,
[UserId] INT NOT NULL
CONSTRAINT [PK_UT] PRIMARY KEY CLUSTERED ([UserTestId] ASC));
用户测试问题
CREATE TABLE [dbo].[UserTestQuestion] (
[UserTestQuestionId] INT IDENTITY (1, 1) NOT NULL,
[UserTestId] INT NOT NULL,
[Answered] BIT DEFAULT ((0)) NOT NULL
CONSTRAINT [PK_UQ] PRIMARY KEY CLUSTERED ([UserTestQuestionId] ASC)
);
- AdminTest 可能有也可能没有 UserTest
- UserTest 总是有 UserTestQuestions
我创建了这个 SQL 来从 AdminTest 和 UserTest 获取数据:
SELECT userTest.StartedDate,
temp.AdminTestId
-- AnsweredCount
-- I want to get a count of the number of rows
-- from the table UserTestQuestions that have
-- the column 'Answered' set to 1 here.
FROM
( SELECT AdminTest.AdminTestId
FROM AdminTest
JOIN AdminTestQuestion ON AdminTest.AdminTestId = AdminTestQuestion.AdminTestId
GROUP BY
AdminTest.AdminTestId
) temp
LEFT OUTER JOIN UserTest ON temp.AdminTestId = UserTest.AdminTestId
-- I want the above join to only join those UserTest tables that
-- have a value of UserId set to for example 25
但现在我被困住了,有两件事我需要帮助。
- 我需要能够仅显示属于给定 UserId 的 UserTests
- 我需要报告 UserTests 中 Answered 设置为 1 的行数。
有人可以就如何将此功能添加到我的 SQL 中给我建议吗?
这是我需要的示例:
AdminTestId UserTestStartedData AnsweredCount
1 1/1/2001 25
2 2/2/2002 10
3
4 4/4/2004 10
【问题讨论】:
标签: sql sql-server join outer-join