SQL: 列中的聚合(按类似分组)
SQL: aggregation (group by like) in a column
我有一个 select,按客户 ID 和日期对过去两个月的客户支出进行分组。我需要做的是为每一行关联该客户在两个月时间段的整个第一周内花费的总金额(当然这将重复一个客户的每一行,但出于某种原因没关系).你知道如何在不使用子查询作为列的情况下做到这一点吗?
我在考虑使用 OVER PARTITION 的某种组合,但无法弄清楚如何......
非常感谢。
拉斐尔
查询:
select customer_id, date, sum(sales)
from transaction_table
group by customer_id, date
如果它是特定的第一周(例如,您总是希望一年中的第一周,并且您的数据集通常包括一月和二月的支出),您可以使用 sum(case...):
select distinct customer_id, date, sum(sales) over (partition by customer_ID, date)
, sum(case when date between '1/1/15' and '1/7/15' then Sales end)
over (partition by customer_id) as FirstWeekSales
from transaction_table
回应以下评论;我不确定这是否是您要查找的内容,因为它涉及子查询,但这是我最好的镜头:
select distinct a.customer_id, date
, sum(sales) over (partition by a.customer_ID, date)
, sum(case when date between mindate and dateadd(DD, 7, mindate)
then Sales end)
over (partition by a.customer_id) as FirstWeekSales
from transaction_table a
left join
(select customer_ID, min(date) as mindate
from transaction_table group by customer_ID) b
on a.customer_ID = b.customer_ID
我有一个 select,按客户 ID 和日期对过去两个月的客户支出进行分组。我需要做的是为每一行关联该客户在两个月时间段的整个第一周内花费的总金额(当然这将重复一个客户的每一行,但出于某种原因没关系).你知道如何在不使用子查询作为列的情况下做到这一点吗? 我在考虑使用 OVER PARTITION 的某种组合,但无法弄清楚如何...... 非常感谢。 拉斐尔
查询:
select customer_id, date, sum(sales)
from transaction_table
group by customer_id, date
如果它是特定的第一周(例如,您总是希望一年中的第一周,并且您的数据集通常包括一月和二月的支出),您可以使用 sum(case...):
select distinct customer_id, date, sum(sales) over (partition by customer_ID, date)
, sum(case when date between '1/1/15' and '1/7/15' then Sales end)
over (partition by customer_id) as FirstWeekSales
from transaction_table
回应以下评论;我不确定这是否是您要查找的内容,因为它涉及子查询,但这是我最好的镜头:
select distinct a.customer_id, date
, sum(sales) over (partition by a.customer_ID, date)
, sum(case when date between mindate and dateadd(DD, 7, mindate)
then Sales end)
over (partition by a.customer_id) as FirstWeekSales
from transaction_table a
left join
(select customer_ID, min(date) as mindate
from transaction_table group by customer_ID) b
on a.customer_ID = b.customer_ID