month
および列の代わりに、テーブルyear
内の各レコードの月を、各月の最初の日を含む列で表した場合:targetRevenue
DATE
ALTER TABLE targetRevenue
ADD COLUMN first DATE;
UPDATE targetRevenue
SET first = STR_TO_DATE(CONCAT_WS('-', year, month, 1), '%Y-%c-%e');
ALTER TABLE targetRevenue
DROP COLUMN year,
DROP COLUMN month;
次に、プロジェクトの合計目標収益を取得できます (開始日と終了日の両方が含まれていると仮定します)。
-- calculate the summation of
SELECT SUM(CONVERT(
-- number of project days in month...
GREATEST(0,
-- ...is calculated as the difference between...
DATEDIFF(
-- ...the last day of the project in this month...
LEAST('2012-03-24', LAST_DAY(first)),
-- ...and the first day of the project in this month...
GREATEST('2012-01-19', first)
)
-- ...plus one because first and last project days were inclusive
+ 1
)
-- multiply by the target revenue for this month
* targetRev
-- divide by the number of days in the month
/ DAY(LAST_DAY(first)),
-- convert result to fixed-point format, to two d.p.
DECIMAL(11,2)
)) AS total
FROM targetRevenue
-- only perform for months in which the project was active
WHERE '2012-01-19' <= LAST_DAY(first) AND first <= '2012-03-24'
sqlfiddleで参照してください。
スキーマを変更できない場合は、への参照をfirst
、その列が上記で更新された値に置き換えることができます。