我有下表:
+ ---------+------------+--------------+-------------+-------------+----------------+ | RecordId | Client | Subscription | Status | Date | Payment Method | + ---------+------------+--------------+-------------+-------------+----------------+ | ABC1234 | John Doe | NetFlex | Renewed | 13 Nov 2018 | Credit Card | | ABC1233 | Jane Smith | SplitiFy | Not Renewed | 01 Sep 2018 | NULL | | ABC1232 | John Doe | NetFlex | Renewed | 13 Nov 2017 | PayPart | | ABC1231 | Jane Smith | SplitiFy | Renewed | 01 Sep 2017 | Cash | | ABC1230 | John Doe | NetFlex | Renewed | 13 Nov 2016 | Cash | + ---------+------------+--------------+-------------+-------------+----------------+
我希望有一个新列,可以在其中为特定客户提供以前的付款方式,如果没有以前的付款,则将其设置为NULL
。换句话说,我想获得以下信息
+ ---------+------------+--------------+-------------+-------------+----------------+-------------------------+ | RecordId | Client | Subscription | Status | Date | Payment Method | Previous Payment Method | + ---------+------------+--------------+-------------+-------------+----------------+-------------------------+ | ABC1234 | John Doe | NetFlex | Renewed | 13 Nov 2018 | Credit Card | PayPart | | ABC1233 | Jane Smith | SplitiFy | Not Renewed | 01 Sep 2018 | None | Cash | | ABC1232 | John Doe | NetFlex | Renewed | 13 Nov 2017 | PayPart | Cash | | ABC1231 | Jane Smith | SplitiFy | Renewed | 01 Sep 2017 | Cash | NULL | | ABC1230 | John Doe | NetFlex | Renewed | 13 Nov 2016 | Cash | NULL | + ---------+------------+--------------+-------------+-------------+----------------+-------------------------+
有人知道如何创建后一个表吗?
答案 0 :(得分:2)
如果您使用的是SQL Server 2012或更高版本,则可以使用LAG
,它将在不使用自联接的情况下返回同一结果集中前一行的数据
因此,在这里我们可以结合使用LAG
和PARTITION BY
以获得预期结果
SELECT RecordId,Client,Subscription,Status,Date,PaymentMethod
,LAG (PaymentMethod, 1, 0) OVER (PARTITION BY Client,Subscription ORDER BY Date)
AS PreviousPaymentMethod
FROM Table