如何按开盘和收盘周分组的示例。
SELECT Organization, Product, Month,
week,
sum(open) AS open,
sum(close) AS close
FROM (
SELECT Organization, Product, Month,
open_week AS week,
count(*) AS open,
0 AS close
FROM tab
GROUP BY Organization, Product, Month, open_week
UNION ALL
SELECT Organization, Product, Month,
close_week AS week,
0 AS open,
count(*) AS close
FROM tab
GROUP BY Organization, Product, Month, close_week
) alias
GROUP BY Organization, Product, Month, week
ORDER BY Organization, Product, Month, week
包含演示 --> http://www.sqlfiddle.com/#!2/01ac3/1
为了简单起见,示例使用month
,close_week
而open_week
不是这样的函数:
WEEK(datefield,5) - WEEK(DATE_SUB(datefield, INTERVAL DAYOFMONTH(datefield)-1 DAY),5)