我试图在SSRS中为数据集编写查询。我有一个名为RequestSchools
的连接表,它连接到另外三个表:
我想获得RequestedSchool (RequestedSchoolTypeId = 3)
我还想要CatchmentSchool (RequestSchoolTypeId = 1)
我附上了我可以与所请求的学校合作的SQL查询图片。我也想要集水学校。感谢任何帮助。
SELECT
pr.PlacingRequestId, s.Name AS RequestedSchool
FROM
PlacingRequests AS pr
INNER JOIN
RequestSchools AS rs ON rs.PlacingRequestId = pr.PlacingRequestId
JOIN
Schools s ON s.SchoolId = rs.SchoolId
WHERE
rs.RequestSchoolTypeId = 3
答案 0 :(得分:0)
我不是100%确定这是正确的,因为我们无法看到架构,源数据或所需输出的完整示例,但我认为这可能是它:
SELECT
pr.PlacingRequestId,
s.Name as RequestedSchool,
cs.Name as CatchmentSchool
FROM
PlacingRequests AS pr
INNER JOIN RequestSchools AS rs
ON rs.PlacingRequestId = pr.PlacingRequestId
INNER JOIN Schools s
on s.SchoolId = rs.SchoolId
AND rs.RequestSchoolTypeId = 3 -- requested school
INNER JOIN Schools cs
on cs.SchoolId = rs.SchoolId
AND rs.RequestSchoolTypeId = 1 -- catchment school
如果不是您的意思,请尽快更新,并且您可以按照指示澄清问题。
答案 1 :(得分:0)
根据我对您的要求的理解,您将需要多个连接而不是where子句中的另一个AND条件。因此,我们可以省略这里的位置,并再次将学校与学校一起加入CatchmentSchool,因为我们已经为Requestedschool做过一次。唯一的区别是我们在加入时使用requestedtypeid和catchmenttypeid值。
Select
pr.PlacingRequestId,
rs.Name as RequestedSchool
cs.Name as CatchmentSchool
FROM
PlacingRequests AS pr
INNER JOIN RequestSchools AS rrs
ON rrs.PlacingRequestId = pr.PlacingRequestId
and rrs.RequestSchoolTypeId = 3
JOIN Schools rs
on rs.SchoolId = rrs.SchoolId
INNER JOIN RequestSchools AS crs
ON crs.PlacingRequestId = pr.PlacingRequestId
and crs.RequestSchoolTypeId = 1
JOIN Schools cs
on cs.SchoolId = crs.SchoolId
希望这会有所帮助......
答案 2 :(得分:0)
执行此操作的最佳方法是使用CASE函数,但我不知道您使用的是哪个RDBMS,因此这里是强力方法:只需将查询作为两个子查询运行,每个子查询指定不同的类型ID然后加入他们。它会是这样的:
SELECT DISTINCT catch.placingrequestid, catch.catchmentschool, requested.requestedschool
FROM
(SELECT pr.placingrequestid, s.nam as catchmentschool
FROM (PlacingRequest pr
INNER JOIN RequestSchools rs ON pr.placingrequestid = rs.placingrequestid)
INNER JOIN School s ON rs.schoolid = s.schoolid
WHERE rs.requestschooltypeid = 1) catch
INNER JOIN
(SELECT pr.placingrequestid, s.nam as requestedschool
FROM (PlacingRequest pr
INNER JOIN RequestSchools rs ON pr.placingrequestid = rs.placingrequestid)
INNER JOIN School s ON rs.schoolid = s.schoolid
WHERE rs.requestschooltypeid = 3) requested
ON catch.placingrequestid = requested.placingrequestid