ich eine Tabelle von totes haben gehen oder sein in benannte Stationen [Tote], wie folgt aus:SQL: Spread Count() durch die Bedingungen in mehreren Spalten
Id Barcode Checksum PackageType Sts Destination LastStationExit LastUpdated
----------- ------------------ ----------- ----------- ----------- ----------- --------------- -----------------------
-2147483645 777000000000000001 586965230 0 1 NULL MS32 2016-04-19 14:15:32.577
-2147483644 777000000000000002 821846254 0 1 MS01 NULL 2016-04-19 15:08:16.140
-2147483643 777000000000000003 1174167790 0 1 NULL MS02 2016-04-19 15:08:20.340
-2147483642 777000000000000004 1543266542 0 1 NULL MS31 2016-04-19 15:08:24.510
-2147483641 777000000000000005 3424831 0 1 NULL MS01 2016-04-19 15:08:31.060
-2147483640 777000000000000006 573850175 0 1 MS01 NULL 2016-04-19 15:08:34.200
ich einen anderen Tisch haben, die enthält alle bestehende Station namens [MezzanineStation]:
Name
----
MS01
MS02
MS11
MS12
MS21
MS22
MS31
MS32
ich für jede Station zu zählen bin versucht, wie viele Behälter zu (Ziel = Station) gehen und wie viele Behälter sind in die Station (LastStationExit = Station).
Ich schrieb die folgende Anfrage, die korrekt funktioniert:
-- Création d'une variable tampon pour isoler les bacs concernés par le calcul
DECLARE @FilteredToteExtract TABLE
(
Destination Varchar(4),
LastStationExit Varchar(4)
)
INSERT INTO @FilteredToteExtract([Destination],[LastStationExit])
SELECT [Destination],[LastStationExit]
FROM [Tote] T
WHERE [PackageType]=0
AND LastUpdated>=DATEADD(HOUR,-12,GETDATE())
AND EXISTS (SELECT * FROM [MezzanineStation] MS WHERE MS.[Name]=T.[Destination] OR MS.[Name]=T.[LastStationExit])
-- Calcul de l'occupation (prévue et courante) des gares de la mezzanine
SELECT DISTINCT MS.Name,T_Destination.[Count] AS NbTotesOngoing,T_LastStationExit.[Count] AS NbTotesInside
FROM [MezzanineStation] MS
LEFT JOIN
(SELECT
Destination,
COUNT(*) AS [Count]
FROM @FilteredToteExtract
GROUP BY Destination
) T_Destination
ON MS.Name = T_Destination.Destination
LEFT JOIN
(SELECT
LastStationExit,
COUNT(*) AS [Count]
FROM @FilteredToteExtract
GROUP BY LastStationExit
) T_LastStationExit
ON MS.Name = T_LastStationExit.LastStationExit
Es gibt mir diese Art von Ergebnis:
Name NbTotesOngoing NbTotesInside
---- -------------- -------------
MS01 2 1
MS02 NULL 1
MS11 NULL NULL
MS12 NULL NULL
MS21 NULL NULL
MS22 NULL NULL
MS31 NULL 1
MS32 NULL NULL
sind hier der Index, den ich auf dem [Tote] Tabelle erstellt:
CREATE INDEX IX_Tote_PackageType ON [Tote]([PackageType])
CREATE INDEX IX_Tote_LastStationExit ON [Tote]([LastStationExit])
CREATE INDEX IX_Tote_LastUpdated ON [Tote]([LastUpdated])
Glauben Sie, dass diese Anfrage optimiert werden kann?
Warum wurde ich abgelehnt? Ich dachte, die richtige und ordentliche Antwort zu geben wäre etwas Nettes. –