2013-02-26 92 views
0

我已經寫了下面的查詢,但它沒有在日期上正確分組,並返回2行,實際上應該由GROUP BY合併爲一行。GROUP BY正在返回錯誤的值?

select i.overridedate, 
     month(i.Overridedate), 
     count(i.id)as count, 
     sum(case when oi.rating <50 then 1 else 0 end) as unfav, 
     sum(case when oi.Rating =50 then 1 else 0 end) as neu, 
     sum(case when oi.Rating >50 then 1 else 0 end) as fav, 
     avg(oi.Rating)as 'Av Rating' 
from Items i (nolock) 

inner join ItemOrganisations oi (nolock) on i.ID= oi.ItemID 
inner join Lookup_ItemTypes it (nolock) on it.ID = i.ItemTypeID 
inner join Batches b (nolock) on b.ID=i.BatchID 
inner join Lookup_ItemStatus lis (nolock) on lis.ID = i.StatusID 
inner join Lookup_BatchStatus lbs (nolock) on lbs.ID = b.StatusID 
inner join Lookup_BatchTypes bt on bt.id = b.Typeid 

where lbs.Name = 'Completed by Analyst' 
     or lbs.Name='Delivered/Imported into Neptune Online' 
     and lis.Name = 'Complete' 
     and i.IsRelevant = 1 
     and bt.Name = 'Live' 
    group by i.overridedate, Month(i.OverrideDate) 
    having i.OverrideDate between '2012-07-01 00:00:00.000' and '2012-09-30 00:00:00.000' 

正如你所看到的,最後兩行代表了7個月的數據不會被分組:

NULL  NULL    1  0  1  0  1  55 
2013-01-03 00:00:00.000  1  1  1  0  0  10 
2012-05-28 00:00:00.000  5  7  1  0  1  50 
2012-06-01 00:00:00.000  6  7  1  0  0  20 
2012-07-10 00:00:00.000  7  1  0  0  0  NULL 
2012-07-11 00:00:00.000  7  8  1  0  6  66 
+8

刪除i.overridedate從你的SELECT和GROUP BY語句。如果需要添加YEAR。 – sgeddes 2013-02-26 16:12:02

+4

@sgeddes像這樣的評論應該張貼爲答案;-) – Lamak 2013-02-26 16:13:33

+2

@sgeddes這應該是一個答案,而不是評論。 – dasblinkenlight 2013-02-26 16:14:59

回答

3

group by是正確的。你爲什麼在其中包含重寫日期?

也許你的選擇應該是:

select min(i.overridedate), month(i.Overridedate), 
. . . 
group by month(i.Overridedate) 

而且,我堅決與說,包括當年的評論一致認爲:

select min(i.overridedate), year(i.Overridedate), month(i.Overridedate), 
. . . 
group by year(i.Overridedate), month(i.Overridedate) 
+0

我有一個關於查詢的條款,忘記了包括,基本上即時通過兩個日期範圍,但不能分組通過這些日期範圍,因爲它不允許我通過外部參考,任何想法我可以做到這一點? – Xerxes 2013-02-26 16:38:22

+0

@xerxes ...我認爲你應該把它作爲一個單獨的問題,這是完全不同的問題。 – 2013-02-26 16:39:55