2016-10-14 2 views
1

Ich habe diese Anfrage:Warum hat diese Abfrage zwei Auswahlmöglichkeiten?

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, 

Diese Abfrage funktioniert wie erwartet, aber ich kann nicht verstehen, warum es zwei wählt hat, warum es sie braucht? Bitte erklären Sie es mir. Vielen Dank.

+7

Der innere Select ist eine abgeleitete Tabelle genannt. Sehr praktisch, wenn Sie 'group by' machen, um zu vermeiden, dass komplexe Ausdrücke doppelt geschrieben werden. (Was laut ANSI SQL nicht einmal erlaubt ist.) – jarlh

+2

Scheint nicht, dass es in diesem Fall wirklich benötigt wird. Sie können die Gruppierung in einem select machen und die 'sum (case ... end)' Sachen machen. – LukStorms

Antwort

3

Wie Sie diese Abfrage Verdacht nicht brauchen zwei wählt und konnte ohne Unter Abfrage neu geschrieben werden:

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 

Anmerkung: Mit table aliases

Verwandte Themen