为什么这个查询有两个选择?

时间:2016-10-14 07:36:59

标签: sql sql-server

我有这个问题:

SELECT         WorkId, RegisterDate, sum(RoomType1) As RoomType1, sum(RoomType2) As RoomType2, sum(RoomType3) As RoomType3, sum(RoomType4) As RoomType4, sum(RoomType5) As RoomType5, sum(RoomType6) As RoomType6, sum(RoomType7) As RoomType7, sum(RoomType8) As RoomType8
FROM (

SELECT     dbo.[Work].WorkId, dbo.[Work].RegisterDate, 

case dbo.Floor.RoomType when 1 then 1 else 0 end as RoomType1,
        case dbo.Kat.RoomType when 2 then 1 else 0 end as RoomType2,


FROM            dbo.Belediye INNER JOIN
                         dbo.[Is] ON dbo.Municipality.MunicipalityId= dbo.[Is].MunicipalityWorkId INNER JOIN
                         dbo.Look ON dbo.[Work].LookWorkId = dbo.Look.LookId ,
WHERE        (dbo.Look.LocationIS NOT NULL)

) E
GROUP BY WorkId, 

此查询按预期工作,但我无法理解为什么它有两个选择,为什么需要它们?请向我解释一下。感谢。

1 个答案:

答案 0 :(得分:3)

如您所怀疑此查询不需要两个选择并且可以在没有子查询的情况下重写:

SELECT  i.IsId, 
        i.KayitTarihi, 
        SUM(case k.OdaTipi when 1 then 1 else 0 end) as RoomType1,
        SUM(case k.OdaTipi when 2 then 1 else 0 end) as RoomType2,
        SUM(case k.OdaTipi when 3 then 1 else 0 end) as RoomType3,
        SUM(case k.OdaTipi when 4 then 1 else 0 end) as RoomType4,
        SUM(case k.OdaTipi when 5 then 1 else 0 end) as RoomType5,
        SUM(case k.OdaTipi when 6 then 1 else 0 end) as RoomType6,
        SUM(case k.OdaTipi when 7 then 1 else 0 end) as RoomType7,
        SUM(case k.OdaTipi when 8 then 1 else 0 end) as RoomType8
FROM dbo.Belediye b
INNER JOIN dbo.[Is] i
    ON b.BelediyeId = i.BelediyeIsId 
INNER JOIN dbo.YerGorme yg
    ON i.YerGormeIsId = yg.YerGormeId 
INNER JOIN dbo.Kat k
    ON yg.YerGormeId = k.YerGorme_YerGormeId
WHERE yg.Lokasyon IS NOT NULL
GROUP BY i.IsId, i.KayitTarihi

注意:使用table aliases