Quantcast
Channel: Questions in topic: "union-all"
Viewing all articles
Browse latest Browse all 18

Alternative to UNION ALL

$
0
0
![alt text][1]![alt text][2]All, Following is the query, and if run by chunks as select it returns data in no time, but when run as of whole it its taking more than 20 secons, even to produce the data on the ssms . How else can we tune this query . SELECT M.corporateCode, M.MeterAsset as 'meterAssetId', M.operatingDate as 'operatingDate', SUM(selected) as 'selected', SUM(goodreading) as 'goodreadings', SUM(badreading) as 'badreadings' FROM ( --good readings select CONVERT (VARCHAR, r.startDate, 101) as 'operatingDate', r.gs_assetIOD as 'MeterAsset', corporateCode = (select gs_customerKey from SCHEMA1.Asset where gs_customerKey is not null and gs_assetIOD=a.gs_assetIOD and (gs_startDate <= r.startDate and (gs_endDate is null OR gs_endDate > r.startDate ))), b.gs_selected as 'selected', 1 as 'goodreading', 0 as 'badreading' from SCHEMA1.MeterReading r join SCHEMA1.IntervalBlock b on r.meterReadingID=b.meterReadingID join SCHEMA3.AssetIndex a on r.gs_assetIOD=a.gs_assetIOD where a.gs_assetKey<> 'DEFAULT_ASSET' UNION ALL -- bad readings with good asset SELECT CONVERT (VARCHAR, r.gs_readingDate, 101) as 'operatingDate', r.gs_assetIOD as 'MeterAsset', corporateCode = (select gs_customerKey from SCHEMA1.Asset where gs_customerKey is not null and gs_assetIOD=a.gs_assetIOD and (gs_startDate <= r.gs_readingDate and (gs_endDate is null OR gs_endDate > r.gs_readingDate ))), 0 as 'selected', 0 as 'goodreading', 1 as 'badreading' from SCHEMA3.ErrorReading r join SCHEMA2.Meter_Data_Header h on h.meterReadingID=r.errorReadingId join SCHEMA3.AssetIndex a on r.gs_assetIOD=a.gs_assetIOD WHERE a.gs_assetKey<>'-999999' UNION ALL --extra bad readings with unknown asset SELECT CONVERT (VARCHAR, r.gs_readingDate, 101) as 'operatingDate', r.gs_assetIOD as 'MeterAsset', h.AssetID as 'corporateCode', 0 as 'selected', 0 as 'goodreading', 1 as 'badreading' from SCHEMA3.ErrorReading r join SCHEMA2.Meter_Data_Header h on h.meterReadingID=r.errorReadingId join SCHEMA3.AssetIndex a on r.gs_assetIOD=a.gs_assetIOD WHERE a.gs_assetKey='-999999' and h.AssetID is not null ) M where M.corporateCode is not null GROUP BY M.corporateCode, M.MeterAsset, M.operatingDate [1]: http://ask.sqlservercentral.com//upfiles/exec_1.jpg [2]: http://ask.sqlservercentral.com//upfiles/exec.png

Viewing all articles
Browse latest Browse all 18

Trending Articles