如何按列具有特定值的组进行求和

时间:2017-03-25 21:29:26

标签: mysql sql

我有一个像这样的数据表

| start_date               | end_date             |     sales    | is_finished |
|:------------------------:|---------------------:|:------------:|:------------:
| 2017-03-24 09:11:00      |  2017-03-24 09:11:00 |     30       |       1
| 2017-03-24 08:30:00      |  2017-03-24 08:30:00 |     50       |       1
| 2017-03-24 08:14:00      |  2017-03-24 08:14:00 |     100      |       1
| 2017-03-24 07:30:00      |  2017-03-24 07:45:00 |     200      |       0 
| 2017-03-24 07:00:00      |  2017-03-24 07:00:00 |     150      |       1 
| 2017-03-24 06:40:00      |  2017-03-24 06:50:00 |     450      |       0

我需要通过start_date和end_date对行进行分组,考虑到它也被分组,其中开始日期和结束日期属于1的行。我还需要每个子集的de SUM。

我需要获得下一个结果

| start_date               | end_date             |   SUM(sales) |
|:------------------------:|---------------------:|:------------:|
| 2017-03-24 09:11:00      |  2017-03-24 09:11:00 |     30       |
| 2017-03-24 08:30:00      |  2017-03-24 08:30:00 |     50       |
| 2017-03-24 07:30:00      |  2017-03-24 08:14:00 |     300      |
| 2017-03-24 06:40:00      |  2017-03-24 07:00:00 |     600      | 

我有一个查询,但我遇到的问题是,当有两行 is_finished 值为1时,它们会被分组。

我的查询是:

SELECT SUM(sales) , MIN(start_date) , MAX(end_date) 
FROM sales 
GROUP BY 
start_date > (SELECT start_date FROM sales WHERE is_finished = 1  ORDER BY end_date ASC LIMIT 1 OFFSET 1 ),
 end_date <= (SELECT end_date FROM sales WHERE is_finished = 1  ORDER BY end_date ASC LIMIT 1)
ORDER BY end_date DESC

使用上面的查询让我接近预期的结果,但它不能很好地工作。

提前致谢。

2 个答案:

答案 0 :(得分:2)

这可能会有所帮助,

SELECT MIN(START_DATE) START_DATE
  , MAX(END_DATE) END_DATE
  , SUM(SALES) SUM_SALES
FROM (
  SELECT START_DATE
    , END_DATE
    , SALES
    , SALES_ID
    , ROW_NUMBER() OVER (PARTITION BY START_DATE, END_DATE ORDER BY SALES_ID) RNK
  FROM (
    SELECT SALES.START_DATE
      , SALES.END_DATE
      , SALES.SALES
      , SALES_ID 
    FROM
    SALES, (
      SELECT END_DATE
        , ROW_NUMBER() OVER (ORDER BY END_DATE) SALES_ID
      FROM SALES
      WHERE IS_FINISHED = 1
    ) SALES_ID
    WHERE SALES.START_DATE <= SALES_ID.END_DATE
      AND SALES.END_DATE <= SALES.END_DATE
  )
)
WHERE RNK = 1
GROUP BY SALES_ID
ORDER BY START_DATE DESC

答案 1 :(得分:1)

请尝试这个

SELECT SEDates.sdate as start_date,SEDates.edate as end_date,SUM(sales)
FROM sales s INNER JOIN
  (SELECT end_date as edate,is_finished,
          @prev as prev,
        CASE WHEN (@prev IS NULL OR @prev = 1) THEN @sdate := start_date
          ELSE @sdate
        END as sdate,
        @prev := is_finished as temp
   FROM sales,(SELECT @prev:=NULL)t
   ORDER BY start_date
   )SEDates
ON s.start_date BETWEEN SEDates.sdate AND SEDates.edate
WHERE SEDates.is_finished = 1
GROUP BY SEDates.sdate,SEDates.edate
ORDER BY SEDates.edate DESC

sqlfiddle