SQL Server:确定新列中的二进制状态的查询,是否按组列出最新行?

时间:2018-10-12 17:25:50

标签: sql sql-server

四处寻找类似情况,但找不到解决方案。也许不使用临时表太复杂了?

我希望能够创建一个新列来显示客户是否曾经使用过优惠券。除此之外,还希望提取最近购买的商品,并按姓氏排序。

我已经能够通过分区来获取最新的交易,但是找不到逻辑来找到优惠券用户,这​​可以一步完成吗?还是必须将其输出到临时表中?

输入数据:

TransDateTime       TransID CustID  FirstName   LastName    NumItems    TotalAmt    CouponUsed
2018-01-09 11:57:24 39451634836 334096  Al  Einstein    5   $1,420.44   Coupon
2018-01-14 17:15:25 39451634837 299080  George  Clooney 1   $816.64 
2018-01-15 19:34:42 39451634838 212950  Stephanie   Germanauto  2   $2,583.64   
2018-01-15 22:32:06 39451634839 258006  Sandy   Bullock 2   $718.36 
2018-01-16 23:34:23 39451634840 212950  Stephanie   Germanauto  3   $1,432.63   
2018-01-18 09:38:39 39451634841 299080  George  Clooney 8   $1,073.50   
2018-01-18 19:36:42 39451634842 258006  Sandy   Bullock 4   $1,035.75   Coupon
2018-01-20 05:58:48 39451634843 334096  Al  Einstein    3   $1,145.06   
2018-01-25 12:16:11 39451634844 212950  Stephanie   Germanauto  7   $1,059.55   
2018-01-31 11:09:41 39451634845 258006  Sandy   Bullock 6   $633.98 Coupon
2018-02-02 14:17:44 39451634846 299080  George  Clooney 9   $925.55 
2018-02-03 19:57:32 39451634847 212950  Stephanie   Germanauto  6   $685.47 Coupon

输出数据:

TransDateTime   TransID CustID  FirstName   LastName    NumItems    TotalAmt    CouponUsed  CouponCust
2018-01-31 11:09:41 39451634845 258006  Sandy   Bullock 6   $633.98     Coupon  Yes
2018-02-02 14:17:44 39451634846 299080  George  Clooney 9   $925.55         
2018-01-20 05:58:48 39451634848 334096  Al  Einstein    3   $1,145.06       Yes
2018-02-03 19:57:32 39451634847 212950  Stephanie   Germanauto  6   $685.47     Coupon  Yes

有人有什么想法吗?

预先感谢您指出正确的方向。

1 个答案:

答案 0 :(得分:1)

一种选择是使用窗口功能Max() over ()

示例

;with cte as (
Select *
      ,CouponCust = max(case when CouponUsed='Coupon' then 'Yes' else 'No' end) over (Partition By CustID)
      ,RN         = Row_Number() over (Partition By CustID order by TransDateTime Desc)
 From  YourTable
) 
Select *
 From  cte 
 Where RN=1

返回

enter image description here