给定周内的交易数量

时间:2017-02-17 21:00:49

标签: sql postgresql

我有这个专栏Actual_Date。 2017年12月2日结束的一周发生了八笔交易。我正在努力研究一个SQL片段,它将为我提供上周发生的交易次数(从2017年2月2日星期一到2017年12月2日星期日)。我已经尝试将天数改为1,2,3等。而且sql仍​​然没有向我提供正确的交易次数。我可以在脚本中添加哪些内容,为我提供数字8?

Actual_Date 
01/31/2017
01/30/2017
01/30/2017
01/30/2017
02/04/2017
02/05/2017
02/06/2017     1
02/10/2017     2
02/08/2017     3
02/06/2017     4
02/12/2017     5
02/06/2017     6
02/06/2017     7
02/12/2017     8     <------------ Number of Transactions

我的剧本:

select coalesce(count(case when Actual_Date = (date_trunc
('week',Actual_Date") + '4 days'::interval)::date
                     then Actual_Date
                      end),0) "This Week"
                      from mysqltable

1 个答案:

答案 0 :(得分:1)

根据您在上面提供的数据,您可以执行此类操作;

CREATE TABLE Transactions  (
  id INT PRIMARY KEY ,
  actual_date DATE 
);

INSERT INTO Transactions (id, actual_date) VALUES
  ( 1, '2017-01-31'),
  ( 2, '2017-01-30'),
  ( 3, '2017-01-30'),
  ( 4, '2017-01-30'),
  ( 5, '2017-02-04'),
  ( 6, '2017-02-05'),
  ( 7, '2017-02-06'),
  ( 8, '2017-02-10'),
  ( 9, '2017-02-08'), 
  (10, '2017-02-06'),
  (11, '2017-02-12'),     
  (12, '2017-02-06'),
  (13, '2017-02-06'),   
  (14, '2017-02-12'); `

对Postgresql执行以下查询:

SELECT 
  actual_date as "Acutal_Date",

  extract(week FROM actual_date) as "Week_Number",

  SUM(
   COUNT(*)) 
   OVER (
     PARTITION BY extract(week FROM actual_date) 
     ORDER BY actual_date
   ) as "Weekly_Count"
FROM 
  Transactions 
GROUP BY actual_date
ORDER BY actual_date;

或者,如果使用MySQL,请使用:

SELECT 
  actual_date as "Actual_Date",

  WEEKOFYEAR(actual_date) as "Week_Number",

  (SELECT 
     COUNT(*) 
   FROM
     Transactions T
   WHERE
     WEEKOFYEAR(T.actual_date) = WEEKOFYEAR(Transactions.actual_date) AND
     T.actual_date <=  Transactions.actual_date) as "Weekly_Count"
FROM 
  Transactions 
GROUP BY actual_date
ORDER BY actual_date;

将产生:

┌─────────────┬─────────────┬──────────────┐
│ Acutal_Date │ Week_Number │ Weekly_Count │
├─────────────┼─────────────┼──────────────┤
│ 2017-01-30  │           5 │            3 │
│ 2017-01-31  │           5 │            4 │
│ 2017-02-04  │           5 │            5 │
│ 2017-02-05  │           5 │            6 │
│ 2017-02-06  │           6 │            4 │
│ 2017-02-08  │           6 │            5 │
│ 2017-02-10  │           6 │            6 │
│ 2017-02-12  │           6 │            8 │
└─────────────┴─────────────┴──────────────┘