SQL:显示产品在6个月的数据中出现的日期

时间:2018-01-26 00:06:46

标签: mysql sql mysql-workbench

我对sql很新,但有一个问题我似乎无法找到答案。

我需要找一个报告中某个产品出现的月数等于6的月份。但是,产品可能不会在连续几个月出现,每月出现多次,并且有些产品尚未在6个月内销售。

我有一个包含以下属性的数据库:

Entry_Id    Product_Name    Sold_Date    Payment_Amount     Segment
======================================================================
112341      ABC Product    2017/12/20        10.50         Segment 1
112342      123 Product    2016/08/21        11.20         Segment 1
112343      ABC Product    2017/12/20        11.50         Segment 1
112344      123 Product    2017/08/21        11.20         Segment 1
112345      123 Product    2017/06/12        11.20         Segment 1
112346      123 Product    2016/06/21        11.20         Segment 1
112347      123 Product    2016/05/02        11.20         Segment 1
112348      123 Product    2015/04/01        11.20         Segment 1
112348      123 Product    2018/01/05        11.20         Segment 1

我想得到以下效果

Product_Name      Date where N = 6    segment
=================================================
ABC Product            N/A            Segment 1 
123 Product        2018/01/05         Segment 1

月份的日期并不重要,只是它出现的月数等于6的月份。

这是我的第一个问题,我会尽可能地积极参与,请提出任何澄清问题。

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用相关子查询执行此操作:

select t.*
from t
where 6 = (select count(distinct year(t2.sold_date), month(t2.sold_date))
           from t t2
           where t2.segment = t.segment and and t2.product = t.product and
                 t2.sold_date <= t.sold_date
          );

由于count(distinct),这将显示第6个月的所有记录。此外,这不是特别有效,但它只使用标准SQL。

您可以将每个细分/产品汇总到一行:

select t.segment, t.product, min(t.sold_date)
from t
where 6 = (select count(distinct year(t2.sold_date), month(t2.sold_date))
           from t t2
           where t2.segment = t.segment and and t2.product = t.product and
                 t2.sold_date <= t.sold_date
          )
group by t.segment, t.product;

答案 1 :(得分:0)

使用GROUP BYCOUNT()计算每件商品的销售月数,并使用HAVING来过滤结果。

SELECT t1.product_name, max_date, segment
FROM yourTable AS t1
JOIN (
    SELECT product_name, MAX(sold_date) AS max_date
    FROM yourTable
    GROUP BY product_name
    HAVING COUNT(DISTINCT YEAR(sold_date), MONTH(sold_date)) >= 6
) AS t2 ON t1.product_name = t2.product_name AND t1.sold_date = t2.max_date

t2子查询查找至少6个月内销售的所有产品。将其与表格连接会查找具有最后日期的行,因此可以选择其segment列。

如果您希望包含至少6个月未售出的产品,并且该列中包含N/A,则可以将测试移出子查询。

SELECT product_name, IF(month_count >= 6, max_date, "N/A") AS last_date, segment
FROM yourTable AS t1
JOIN (
    SELECT product_name, MAX(sold_date) AS max_date, COUNT(DISTINCT YEAR(sold_date), MONTH(sold_date)) as month_count
    FROM yourTable
    GROUP BY product_name
) AS t2 ON t1.product_name = t2.product_name AND t1.sold_date = t2.max_date