我的数据库中有三个表。
数据如下所示:
我正在使用以下SQL:
SELECT
AdminTest.AdminTestId,
AdminTest.Title,
COUNT(AdminTestQuestion.AdminTestQuestionId) Questions,
AdminTest.Price,
UserTest.PurchaseDate
FROM AdminTest
LEFT OUTER JOIN UserTest
ON AdminTest.AdminTestId = UserTest.AdminTestId
JOIN AdminTestQuestion
ON AdminTest.AdminTestId = AdminTestQuestion.AdminTestId
GROUP BY
AdminTest.AdminTestId,
AdminTest.Title,
UserTest.UserId
这给我一个这样的报告:
AdminTestId Title Questions Price PurchaseDate
1 Test1 10 0
2 Test2 20 0 1/1/2011
3 Test3 10 10 2/2/2012
有人可以建议我如何修改它,以便SQL采用UserId
参数,以便它可以正确显示特定用户购买的测试:
当我为UserId参数提供1
的值时,我希望看到这一点:
AdminTestId Title Questions Price PurchaseDate
1 Test1 10 0
2 Test2 20 0 1/1/2011
3 Test3 10 10
当我为UserId参数提供2
的值时,我希望看到这一点:
AdminTestId Title Questions Price PurchaseDate
1 Test1 10 0
2 Test2 20 0
3 Test3 10 10 2/2/2012
我到目前为止所尝试的是将UserId的WHERE子句添加到select的AdminUser部分。但这似乎不起作用。我希望有人能指出我正确的方向。
在这里参考UserTest表的DDL,我想以某种方式过滤掉UserId:
CREATE TABLE [dbo].[UserTest] (
[UserTestId] INT IDENTITY (1, 1) NOT NULL,
[AdminTestId] INT NOT NULL,
[UserId] INT NOT NULL,
[PurchaseDate] DATETIME NOT NULL,
CONSTRAINT [PK_UserTest] PRIMARY KEY CLUSTERED ([UserTestId] ASC)
);
答案 0 :(得分:5)
扩展@RichardHansell所说的......
您可以通过向' ON'添加内容来过滤JOIN。脚本的子句。 ON子句不必只是两个表之间的链接,您也可以添加其他过滤器。像这样......
SELECT AdminTest.AdminTestId,
AdminTest.Title,
COUNT(AdminTestQuestion.AdminTestQuestionId) Questions,
AdminTest.Price,
UserTest.PurchaseDate
FROM AdminTest
LEFT OUTER JOIN UserTest
ON AdminTest.AdminTestId = UserTest.AdminTestId
AND UserTest.UserId = @FilteredUserId
JOIN AdminTestQuestion
ON AdminTest.AdminTestId = AdminTestQuestion.AdminTestId
GROUP BY AdminTest.AdminTestId, AdminTest.Title, UserTest.UserId
答案 1 :(得分:2)
如果您将参数test放在Left Outer Join的ON子句中,您应该得到以下结果:
...
LEFT OUTER JOIN UserTest
ON AdminTest.AdminTestId = UserTest.AdminTestId
AND UserTest.UserId = @UserId
...