分组周

时间:2013-10-11 12:20:12

标签: mysql group-by week-number

我想显示过滤器中所选日期范围的打开和关闭计数。数据将按组织产品,月和周分组。但问题是我计算开放和关闭周数。 Open有一个单独的列,close有不同的..它可以将它分组在任何单个字段上,就像我想要的那样:

Week             Open         Close

0                  3            5
1                  2            0  

如果关闭日期不在第2周。第2周存在开放日期,则应显示如下:

Week          Open      Close

2              3          0

如何在两个列上对其进行分组?

请帮忙。

1 个答案:

答案 0 :(得分:0)

如何按开放和关闭周分组的示例。

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

为简单起见,示例使用monthclose_weekopen_week来代替以下函数:
WEEK(datefield,5) - WEEK(DATE_SUB(datefield, INTERVAL DAYOFMONTH(datefield)-1 DAY),5)