1

我为我的项目做统计功能。我有一些字段的订单表:

  • prouct_id,
  • amount,
  • order_date.

客户要求我进行自动缩放统计:我得到MIN(order_date)aproduc_id和当前日期来计算天数

  • 如果大约〜1个月的天数==>按周显示产品的统计信息

  • 如果大约〜1年的日子==>按月显示产品的统计信息

  • 如果天数>= 2 年 ==> 按年份显示产品的统计信息

我希望能收到大家关于如上统计的想法、例子。

4

1 回答 1

1

You didn't specify what RDBMS is this. So let me assume that it is SQL Server, and you can do this:

;WITH MinDates AS
(
    SELECT 
      produc_id,
      MIN(order_date) order_date
    FROM products
    GROUP BY produc_id
), DatesWithIntervals AS
(
    SELECT 
      product_id,
      order_date,
      CASE 
        WHEN ABS(DATEDIFF(dd, order_date, GETDATE())) < 31      THEN 1
        WHEN ABS(DATEDIFF(dd, order_date, GETDATE())) < 365     THEN 2
        WHEN ABS(DATEDIFF(dd, order_date, GETDATE())) < 365 * 2 THEN 3 
        ELSE 4
      END "Interval"
    FROM MinDates
)
SELECT
  product_id,
  order_date
  ...
FROM DatesWithIntervals 
--Do your statics here

You didn't specify what statistics do you want to compute. But you should be able to do whatever statistics you want to do using the last cte: DatesWithIntervals depending on the field Interval and I will leave it as a practice for you.

Edit: For MySQL, just replace all these CTEs with subqueries like so:

SELECT
  product_id,
  order_date
      ...
FROM
(
    SELECT 
      product_id,
      order_date,
      CASE 
        WHEN ABS(DATEDIFF(dd, order_date, GETDATE())) < 31      THEN 1
        WHEN ABS(DATEDIFF(dd, order_date, GETDATE())) < 365     THEN 2
        WHEN ABS(DATEDIFF(dd, order_date, GETDATE())) < 365 * 2 THEN 3 
        ELSE 4
      END "Interval"
    FROM
    (
         SELECT 
          produc_id,
          MIN(order_date) order_date
         FROM products
         GROUP BY produc_id  
    ) MinDates
) DatesWithIntervals 
--Do your statics here
于 2012-11-20T08:58:28.623 回答