我有一个表格,其中包含客户名称列,购买金额列以及购买日期列。有没有一种简单的方法可以找到客户每天第一次花费多少钱?
所以我有
Name | Purchase Amount | Date
Joe 10 9/1/2014
Tom 27 9/1/2014
Dave 36 9/1/2014
Tom 7 9/2/2014
Diane 10 9/3/2014
Larry 12 9/3/2014
Dave 14 9/5/2014
Jerry 16 9/6/2014
我想要像
这样的东西Date | Total first Time Purchase
9/1/2014 73
9/3/2014 22
9/6/2014 16
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:3)
以下是标准SQL,适用于几乎所有DBMS
select date,
sum(purchaseamount) as total_first_time_purchase
from (
select date,
purchaseamount,
row_number() over (partition by name order by date) as rn
from the_table
) t
where rn = 1
group by date;
派生表(内部选择)选择所有"第一次"根据日期购买和聚合外部。
答案 1 :(得分:1)
这里的两个关键概念是aggregates
和sub-queries
,您使用的dbms的详细信息可能会改变确切的实现,但基本概念是相同的。
在SQL Server中,它可能如下所示:
select Date, [totalFirstTimePurchases] = sum(PurchaseAmount)
from (
select t.Date, t.PurchaseAmount, t.Name
from table1 t
join (
select Name, [firstDate] = min(Date)
from table1
group by Name
) f on t.Name=f.Name and t.Date=f.firstDate
) ftp
group by Date
答案 2 :(得分:0)
如果您使用的是SQL Server,则可以使用sub-queries
或CTE(Common Table Expressions)完成此操作。由于已经有sub-queries
的答案,因此这是CTE版本。
首先,以下内容将标识首次购买的每一行,然后获取按日期分组的值的总和:
;WITH cte
AS (
SELECT [Name]
,PurchaseAmount
,[date]
,ROW_NUMBER() OVER (
PARTITION BY [Name] ORDER BY [date] --start at 1 for each name at the earliest date and count up, reset every time the name changes
) AS rn
FROM yourTableName
)
SELECT [date]
,sum(PurchaseAmount) AS TotalFirstTimePurchases
FROM cte
WHERE rn = 1
GROUP BY [date]