1
我有三張桌子。的測試的表(AdminTest)的屬於用戶(UserTest)和問題屬於每個用戶測試的一個表(UserTestQuestion)測試的表:如何從連接到左外連接的表中獲取計數?
AdminTest
UserTest
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));
UserTestQuestion
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
- 我需要在回答設爲1
的UserTests報告的行數的UserTests有人可以給我建議如何將這個功能添加到我的SQL?
這裏是什麼,我需要一個例子:
AdminTestId UserTestStartedData AnsweredCount
1 1/1/2001 25
2 2/2/2002 10
3
4 4/4/2004 10
非常感謝。我現在會試試這個。 – Alan2 2015-02-08 07:58:03
我想顯示所有AdminTest表以及那些存在的userTest表(具有相同的AdminTestId)並且具有UserId = 25。有沒有一種方法可以離開LEFT OUTER JOIN並且還可以添加到WHERE中以限制UserTest表與25用戶ID? – Alan2 2015-02-08 08:08:03
我想我仍然需要LEFT OUTER JOIN,因爲我想顯示Admin表的列表,即使沒有用戶表。我剛剛爲這個問題添加了一個我需要的輸出示例。我希望它更清楚一點。 – Alan2 2015-02-08 08:14:02