我有一个用户活动表。我有 HWA、活动日期和 groupID。我根据日期范围获得用户活动的季度,即:
日期范围:2011-08-01 - 2012-07-31
Q1 - Aug-Oct
Q2 - Nov-Jan
Q3 - Feb-Apr
Q4 - May-Jul
一些 HWA 是其他 HWA 的替代品。在这些情况下,它们具有相同的 groupID 以表明它们是链接的。在这些情况下,我需要取消重叠的季度。澄清一下,如果两个 HWA 在第 2 季度使用并且它们具有相同的 groupID,那么我只需要为其中一个计算第 2 季度(这无关紧要)。下面是我现在使用的查询,得到的输出是:
SELECT act.HWA, count(act.HWA), m.Status, m.GroupID
FROM (
SELECT
a.HWA, a.Date,
CASE
WHEN MONTH(a.Date) BETWEEN 8 AND 10 THEN 'Q1'
WHEN (MONTH(a.Date) BETWEEN 11 AND 12 OR MONTH(a.Date) = 1) THEN 'Q2'
WHEN MONTH(a.Date) BETWEEN 2 AND 4 THEN 'Q3'
WHEN MONTH(a.Date) BETWEEN 5 AND 7 THEN 'Q4'
END AS quarter,
CASE
WHEN MONTH(a.Date) <= 7 THEN YEAR(a.Date) - 1
ELSE EXTRACT(YEAR_MONTH from a.Date)
END AS quarteryear,
COUNT(*) AS num_activites
FROM activity a
WHERE a.InstitutionNumber = '000000000075'
AND (a.HWA = '001372EADBC4'
OR a.HWA = '180373E241DB'
OR a.HWA = '180373E23DE7')
AND (a.Date between '2011-08-01' and '2012-07-31')
GROUP BY
quarter,
a.HWA
) act, machine m
where act.HWA = m.HWA
group by act.HWA
这会返回:
HWA quarters status groupid
001372EADBC4 3 deleted 59970
180373E23DE7 2 online 59970
180373E241DB 1 deleted 59970
预期结果将是:
HWA 宿舍状态 groupid
001372EADBC4 2 deleted 59970
180373E23DE7 2 online 59970
180373E241DB 0 deleted 59970
这是我通过稍微更改上述查询生成的每个 HWA 的季度列表。您可以看到所有三个 HWA 都有第 3 季度的份额,我希望它们中只有一个拥有第 3 季度的份额:
001372EADBC4 1 deleted 59970
001372EADBC4 2 deleted 59970
001372EADBC4 3 deleted 59970
180373E23DE7 3 online 59970
180373E241DB 3 deleted 59970
180373E23DE7 4 online 59970