Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 每月随机选择1-3个值_Sql_Postgresql - Fatal编程技术网

Sql 每月随机选择1-3个值

Sql 每月随机选择1-3个值,sql,postgresql,Sql,Postgresql,预期结果: 我有一个巨大的数据库,需要从中提取一些数据进行案例研究。 问题是,我需要提取全年的数据,因为我希望能够在案例研究中进行月度分析。因此,我不能限制摘录的日期或限制 因此,我解决这个问题的想法是,根据customer列,每月随机抽取1-3个值 下列条件应适用: 客户可以在结果中多次出现->例如示例中的客户 结果的顺序无关紧要->按随机顺序 你知道这是否可行吗? 如果是,我需要如何修改下面的查询 SELECT s.customer, s.orderID, s.event_date, SUM

预期结果:

我有一个巨大的数据库,需要从中提取一些数据进行案例研究。 问题是,我需要提取全年的数据,因为我希望能够在案例研究中进行月度分析。因此,我不能限制摘录的日期或限制

因此,我解决这个问题的想法是,根据customer列,每月随机抽取1-3个值

下列条件应适用:

客户可以在结果中多次出现->例如示例中的客户 结果的顺序无关紧要->按随机顺序 你知道这是否可行吗? 如果是,我需要如何修改下面的查询

SELECT
s.customer,
s.orderID,
s.event_date,
SUM(s.sales_volume) AS sales_volume
FROM sales s
GROUP BY 1,2,3
ORDER BY random();

它回答了你的问题吗

安顿你的

每月随机对行进行排序,从结果中获取1-3:

SELECT * from (SELECT
customer,
orderID,
event_date,
sales_volume ,
rank() OVER (PARTITION BY date_trunc('month', event_date) ORDER BY random()) as rand
from sales) temp
where rand < 1 + random() * 3
order by event_date
我按事件日期订购,以保持每月的行在一起,并根据您的需要进行更改

您可以通过增加因子来增加获得3行的机会,但将其限制为3,如

where rand < 1 + random() * 6 and rand <= 3

客户E的预期行中的th 200是错误吗?是的,我刚刚修复了它。您需要将客户包括在分区中。@GordonLinoff预期数据似乎说不同只是为了我的文档:
select
  customer,
  orderid,
  event_date,
  sales_volume
from (
  select
    *,
    row_number() over(partition by customer order by random()) seq
  from (
    SELECT
    s.customer,
    s.orderID,
    s.event_date,
    sum(s.sales_volume) AS sales_volume
    FROM sales s
    GROUP BY 1,2,3
  ) volumes
) sample
where seq <= 3
order by customer, seq
SELECT * from (SELECT
customer,
orderID,
event_date,
sales_volume ,
rank() OVER (PARTITION BY date_trunc('month', event_date) ORDER BY random()) as rand
from sales) temp
where rand < 1 + random() * 3
order by event_date
where rand < 1 + random() * 6 and rand <= 3