2013-07-25 34 views
1

得到以下錯誤:外部引用錯誤,當分組月和年

Each GROUP BY expression must contain at least one column that is not an outer reference 

我想有calculatedDrugDistributionHistory通過facilty,月,年的分組列表。我只想盤點哪些月份已導入系統的設施。

我有這個疑問:

select 
    f.name, 
    MONTH(cddh.dateGiven) as 'date_month', 
    YEAR(cddh.dateGiven) as 'date_year' 
from 
    calculatedDrugDistributionHistory cddh 
     inner join facilityIndividuals fi on fi.facilityIndividualId = cddh.facilityIndividualId 
     inner join facilities f on fi.facilityId = f.facilityId 
group by 
    f.name, 
    'date_month', 
    'date_year' 
order by 
    f.name, 
    'date_month', 
    'date_year' 
+0

你正在得到的錯誤是因爲'date_month'和'date_year'一旦這個分組被執行後,就會進入畫面。 –

回答

0

不能在組使用別名by子句。試試這種方式:

select 
    f.name, 
    MONTH(cddh.dateGiven) as date_month, 
    YEAR(cddh.dateGiven) as date_year 
from calculatedDrugDistributionHistory cddh 
inner join facilityIndividuals fi on fi.facilityIndividualId = cddh.facilityIndividualId 
inner join facilities f on fi.facilityId = f.facilityId 
group by 
    f.name, 
    MONTH(cddh.dateGiven), 
    YEAR(cddh.dateGiven) 
order by 
    f.name, 
    date_month, 
    date_year 
+0

感謝resposne Parado - 你的回答是有道理的,但我得到的錯誤是'dateGiven'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY中 – etm124

0

兩個問題。首先,您將單引號用於列別名。使用雙引號或方括號。其次,你需要包括select子句中的所有列,而不聚集功能應該是在group by

select f.name, MONTH(cddh.dateGiven) as date_month, YEAR(cddh.dateGiven) as date_year' 
from calculatedDrugDistributionHistory cddh 
     inner join facilityIndividuals fi on fi.facilityIndividualId = cddh.facilityIndividualId 
     inner join facilities f on fi.facilityId = f.facilityId 
group by f.name, MONTH(cddh.dateGiven), YEAR(cddh.dateGiven) 
order by f.name, date_month, date_year; 

您可以使用列別名在order by,而不是group by

0

GROUP BY不能使用別名,如果你能,你不應該將它們與單引號寫:

select 
    f.name, 
    MONTH(cddh.dateGiven) as date_month, 
    YEAR(cddh.dateGiven) as date_year 
from 
    calculatedDrugDistributionHistory cddh 
     inner join facilityIndividuals fi on fi.facilityIndividualId = cddh.facilityIndividualId 
     inner join facilities f on fi.facilityId = f.facilityId 
group by 
    f.name, 
    MONTH(cddh.dateGiven), 
    YEAR(cddh.dateGiven) 
order by 
    f.name, 
    date_month, 
    date_year 
0
SELECT 
name, 
date_month, 
date_year 

FROM 

(select F.NAME,MONTH(cddh.dateGiven) as date_month, 
    YEAR(cddh.dateGiven) as date_year 

from 
    calculatedDrugDistributionHistory cddh 
     inner join facilityIndividuals fi on fi.facilityIndividualId = cddh.facilityIndividualId 
     inner join facilities f on fi.facilityId = f.facilityId)TEMP 
group by 
    name, 
    date_month, 
    date_year 
order by 
    name, 
    date_month, 
    date_year 

請使用此更新

問候

Ashutosh Arya

相關問題