任何人都可以帮助解决这个T-SQL请求吗?
我有1000张订单的表。许多是同一客户的重复订单。 我试图创建一个查询,显示每个客户的许多消费习惯,以及他们首次订购时使用的促销代码。我可以挑选他们的 使用Top或Max函数的第一个订单日期,但我如何从下表中返回Cust和第一个促销代码?:
Cust Order Order Date Promotion Code
JB001 df445 01/02/2014 Web32
JB001 56456 01/02/2015 Cat85
JB001 5646a 03/04/2012 Email22
JB001 ff55f 25/04/2003 Cat67
JB002 45454 28/09/2011 Cat55
JB002 65488 22/10/2011 Email31
JB002 793gg 15/05/2007 Email22
JB003 5444h 10/10/2014 Web14
JB003 gbnm2 22/10/2014 Autumn21
给这个?:
Cust Promotion Code
JB001 Cat67
JB002 Email22
JB003 Web14
非常感谢,
约翰
答案 0 :(得分:1)
使用Window Function
SELECT cust,[promotion code]
FROM (SELECT cust,
[promotion code],
Row_number()
OVER(
partition BY cust
ORDER BY [order date]) rn
FROM tablename)a
WHERE rn = 1
或使用aggregate
与Group by
一起查找每个客户的最短日期,然后将结果重新加入主表
SELECT cust,
[promotion code]
FROM tablename a
JOIN(SELECT Min([order date]) or_date,
cust
FROM tablename group by cust) b
ON a.cust = b.cust
AND a.[order date] = b.or_date
答案 1 :(得分:1)
您可以使用row_number()
获取每位客户的第一笔订单:
select cust, promotioncode, orderdate
from (select t.*, row_number() over (partition by cust order by orderdate) as seqnum
from orders t
) t
where seqnum = 1;
答案 2 :(得分:0)
您可以使用Window功能。比如,Max over date,按Cust排序按等级划分并选择等级为1的记录。
Select Cust,PromotionCode from
(Select Cust, PromotionCode,
Rank () over (partition by cust order by date)
as rank from records )a
where a.rank=1