1

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

Week             Open         Close

0                  3            5
1                  2            0  

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

Week          Open      Close

2              3          0

如何在两列上进行分组?

请帮忙。

4

1 回答 1

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

为了简单起见,示例使用month,close_weekopen_week
不是这样的函数:
WEEK(datefield,5) - WEEK(DATE_SUB(datefield, INTERVAL DAYOFMONTH(datefield)-1 DAY),5)

于 2013-10-11T16:59:01.120 回答