2016-04-06 15 views
0

aynı tablo, SQL Server katılır:Çoklu Bir tablo binlerce kayıt olması gerekiyordu [item] sahip

ID ItemNo DepartDate Country Item Amount 
    1  1 2016-01-01 France HOTEL 100 
    1  2 2016-01-01 France HOTEL 150 
    1  3 2016-01-01 France MEALS 150 
    2  1 2016-02-01 England HoTEL 150 
    2  1 2016-02-01 England MEALS 200 
    2  1 2016-02-02 England MEALS 200 
    2  1 2016-02-02 WALES MEALS 200 

sonucun Otel sayısına saymak istiyorum yemek ayrı departDate dayalı:

Country hotelCount mealCount 
    France 1    1 
    England 1    2 
    WALES 0    1 


    Select i.Country, Count(distinct iHotel.DepartDate) as hotelCount, Count(distinct iMeal.DepartDate) as mealCount 
    FROm item i 
    left join item iHotel on i.id = v.id and i.Country =iHotel.Country 
    left join item iMeal on i.id = iMeal .id and i.Country =iMeal .Country 
    where i.Country is not null 
    group by i.country 

Ancak, zaman aşımı sorununa neden olduğundan binlerce kayıt için çalışmaz. Her türlü yardım? Çok teşekkürler. Tekrar çalışmıyor Bu sorgu ve sql Fiddle ile çok mutlu değilim

Select i.Country, Count(distinct iHotel.DepartDate) as hotelCount, Count(distinct iMeal.DepartDate) as mealCount 
    FROm item i 
    left join item iHotel on i.id = v.id and i.Country =iHotel.Country 
    left join item iMeal on i.id = iMeal .id and i.Country =iMeal .Country 
    where i.Country is not null 
    group by i.country 

:

Select i.Country, MAX(coalesce(H.CT,0)) as hotelCount , MAX(coalesce(M.CT,0)) as mealCount 
    FROM item i 
    LEFT JOIN 
    (SELECT COUNT(*) as CT,Country, Item 
     FROM item 
     WHERE item = 'HOTEL' GROUP BY Country, Item) H 
     ON H.Country = i.Country AND i.Item = H.item 
    LEFT JOIN 
    (SELECT COUNT(*) as CT,Country, Item 
     FROM item 
      WHERE item = 'MEALS' GROUP BY Country, Item) M 
     ON M.Country = i.Country AND i.Item = M.item 
    GROUP BY i.Country 
+0

Bu sorguda – Strawberry

+1

mysql veya sql-server - birini seçin. – Paddy

+0

Tabloda hangi endeks var? –

cevap

0

, ayrı yemek ve otele bir şey yapmayın Hangi RDBMS kullanıyorsunuz?
İlgili konular