1

我有四张桌子:

Service (serviceId(PK), serviceTypeId, capacity)
Facilitator (facilitatorId(PK), facilitatorName)
ServiceType (serviceTypeId(PK), serviceType)
ServiceFacilitator (serviceId(PK), facilitatorId(PK)) (join entity)

目前'ServiceType'表中的服务类型是酒店和会议中心

“服务”表中的“容量”列包含仅在与 ServiceType.serviceTypeId 相关时才有意义的数字,即根据服务类型表示床或座位。

我需要编写一个查询,它将返回 3 列,名称为:facilitatorName, Beds, Seat

我几乎可以肯定,在存储过程中创建和丢弃临时表是一个糟糕的解决方案,它可能会对未来的可伸缩性等产生负面影响,并且该解决方案涉及到服务表上的自联接。

到目前为止,我的查询如下所示,但没有返回任何行;我错过了什么?

SELECT f.facilitatorName,(SUM(ts1.capacity)) as Beds,(SUM(ts2.capacity)) as Seats

FROM dbo.Facilitator as f,
        dbo.TestService as ts1,
        dbo.TestService as ts2,
        dbo.ServiceFacilitator as sf

WHERE f.facilitatorId = sf.facilitatorId AND
        (sf.serviceId = ts1.serviceId or
        sf.serviceId = ts2.serviceId) and 
        ts1.serviceId = ts2.serviceId and
        ts1.serviceTypeId = '1' and -- type hotel
        ts2.serviceTypeId = '2' -- type conference centre           

GROUP BY f.facilitatorName

将查询一分为二将返回 Beds 和 Seats 的准确结果:

SELECT f.facilitatorName,(SUM(ts1.capacity)) as Beds

FROM dbo.Facilitator as f,
        dbo.TestService as ts1,
        dbo.ServiceFacilitator as sf

WHERE f.facilitatorId = sf.facilitatorId AND
        sf.serviceId = ts1.serviceId and 
        ts1.serviceTypeId = '1'         

GROUP BY f.facilitatorName

SELECT f.facilitatorName,(SUM(ts2.capacity)) as Seats

FROM dbo.Facilitator as f,
        dbo.TestService as ts2,
        dbo.ServiceFacilitator as sf

WHERE f.facilitatorId = sf.facilitatorId AND
        sf.serviceId = ts2.serviceId and 
        ts2.serviceTypeId = '2'         

GROUP BY f.facilitatorName

谢谢..

4

2 回答 2

3

您的查询的一个简单解决方案应该是:

SELECT f.facilitatorName,
       SUM(case when ts.serviceTypeId = '1' then ts.capacity end) as Beds,
       SUM(case when ts.serviceTypeId = '2' then ts.capacity end) as Seats
FROM dbo.Facilitator as f
LEFT JOIN dbo.ServiceFacilitator as sf ON f.facilitatorId = sf.facilitatorId
LEFT JOIN dbo.TestService as ts ON sf.serviceId = ts.serviceId
GROUP BY f.facilitatorName
于 2013-02-07T12:35:57.487 回答
0

您应该为此查询使用 Join。例如:

SELECT f.facilitatorName,(SUM(ts1.capacity)) as Beds,(SUM(ts2.capacity)) as Seats

FROM 
        dbo.ServiceFacilitator as sf 
join dbo.Facilitator as f 
on   sf.facilitatorI = f.facilitatorId
join dbo.TestService as ts1 
on sf.serviceId = ts1.serviceId
join  dbo.TestService as ts1
on sf.serviceId = ts2.serviceId

WHERE 
        ts1.serviceTypeId = '1' and -- type hotel
        ts2.serviceTypeId = '2' -- type conference centre           

GROUP BY f.facilitatorName
于 2013-02-07T13:20:17.433 回答