2011-08-18 33 views
0

我有兩張表。組織和ReturnForms。計算在外表中沒有條目的項目數

的ReturnForm結構爲:

| formID | returnMonth | returnYear | orgID | 

機構按月提交申報表。 returnMonth和returnYear存儲表單的月份/年份,orgID是組織提交表單的fk,formID是returnForm表的pk。

我想統計有多少組織沒有特定月份/年份組合的returnForm。對於單月/年,這是很容易:

SELECT count(*) 
FROM `tblOrganisations` AS `Organisation` 
     LEFT JOIN `tblReturnForms` AS `NoForm` 
     ON (`NoForm`.`orgID` = `Organisation`.`orgID` 
       AND `NoForm`.`returnMonth` = 3 
       AND `NoForm`.`returnYear` = 2010) 
WHERE `NoForm`.`formID` IS NULL 

我遇到的問題是怎麼算多種形式沒有12/2005和當月之間提交。我可以通過在12/2005之間運行每個月/年的關於查詢並對它們進行求和來計算它,但我確信有更好,更優雅的方式來做這件事。

+0

重寫了問題以更好地解釋我遇到的問題。 – Dakota

+0

只需添加,formID是returnForms表的PK。 – Dakota

回答

0

你可以計算最早的年份和月份需要像這樣:

min_year = current_year; 
min_month = current_month - 4; 
if min_month < 1 then 
    min_month = 12 + min_month; 
    min_year = min_year - 1; 
end if; 

create temp table periods(year integer, month integer); 
for month/year in(12/2005 .. min_month/min_year) 
    insert into periods values (year, month); 
loop; 

,然後使用這些在SQL語句中,像這樣:

SELECT 
    `periods`.`year`, 
    `periods`.`month`, 
    count(*), 
FROM 
    `tblOrganisations` AS `Organisation` 
    JOIN periods 
    LEFT JOIN `tblReturnForms` AS `NoForm` ON 
     (`NoForm`.`orgID` = `Organisation`.`orgID` 
      AND 
      `NoForm`.`returnYear` = `period`.`year` 
      AND 
      `NoForm`.`returMonth` <= `periods`.`month`)) 
WHERE 
    `NoForm`.`formID` IS NULL 
GROUP BY 
    `periods`.`year`, 
    `periods.`month` 

這會給你每缺少回報的數返回類型/月/年 - 全部在一個查詢中 - 然後循環遍歷結果。

+0

感謝您的回答。它雖然不完全符合我的要求。我正在尋找一種計算多少個月/年/ orgID沒有returnForms(從2005年12月起)的方法。首先,我的問題並不十分明確。我已經改寫它來更好地解釋我在找什麼。 – Dakota

+0

我想我現在明白你現在的想法。我更新了我的答案。不幸的是,我沒有可用的mysql安裝來測試它。 –