通过查看日期列的最小日期选择不同的值

问题描述 投票:2回答:1

我想补充一点,以我现有的查询,将过滤掉任何销售,通过只取最小日期值出现不止一次/购买。

我已经使用MIN()函数和GROUP BY运营商尝试过,但这样做并不让我选择我需要的其他列,这是假设是我揪成双向电力的视图。

编辑:好吧,我想我想通了。我只是用MIN()函数和GROUP BY子句,但我以前没有使用GROUP BY子句,我很害怕,它会过滤太多行了。我需要所有下面列出列。我还添加了样本数据一起玩。我需要看PaymentDue,只选择第一个筛选出了“复制” ContractPurchaseID的。什么是使用GROUPBY的危险?

样本数据:

PurchaseLogID   StoreID     UserID      ContractPurchaseID  PackageName         PurchaseDate    PaymentDue  PurchaseAmount  EverGreenPrice
118849930       7306        48938416    7825299             Monthly Unlimited   2/11/2019       2/11/2019   84              109
118849935       7306        48938416    7825299             Monthly Unlimited   2/11/2019       3/11/2019   109             109
118404876       6700        22920416    6610879             Monthly Unlimited   3/1/2019        3/1/2019    119             119
118746691       6700        23081863    6240459             Monthly Unlimited   3/1/2019        3/1/2019    159             159
118271837       7308        48668745    7777689             8 Pack Monthly      3/1/2019        3/1/2019    89              89
118271747       7308        48668763    7777679             8 Pack Monthly      3/1/2019        3/1/2019    89              89

查询:

SELECT P.PurchaseLogID, 
    P.StoreID, 
    P.UserID, 
    P.ContractPurchaseID, 
    P.PackageName, 
    P.PurchaseDate, 
    P.PaymentDue, 
    P.PurchaseAmount, 
    C.EvergreenPrice 
FROM PurchaseLog AS P
INNER JOIN ContractPurchases AS C 
    ON P.ContractPurchaseID = C.ContractPurchaseID
INNER JOIN Users AS U 
    ON C.UserID = U.UserID
WHERE P.PaymentDue >= DATEADD(Day, -1, getdate()) 
    AND P.PaymentDue <= DATEADD(Day, +30, getdate())
    AND P.Deleted IS NULL
    AND (P.PaymentDue < C.CancelOn OR C.CancelOn IS NULL)
    AND P.PurchaseAmount <> '0'
    AND (haspastdue IS NULL OR haspastdue = 0)
sql sql-server ssms
1个回答
1
投票

您可以尝试使用row_number()窗函数

select * from
(
SELECT P.PurchaseLogID, P.StoreID, P.UserID, P.ContractPurchaseID, P.PackageName, P.PurchaseDate, P.PaymentDue, P.PurchaseAmount, C.EvergreenPrice,row_number() over(partition by P.PurchaseLogID, P.StoreID, P.UserID, P.ContractPurchaseID order by P.PaymentDue) as rn
FROM PurchaseLog AS P
INNER JOIN ContractPurchases AS C ON P.ContractPurchaseID = C.ContractPurchaseID
INNER JOIN Users AS U ON C.UserID = U.UserID
WHERE P.PaymentDue >= DATEADD(Day, -1, getdate()) AND P.PaymentDue <= DATEADD(Day, +30, getdate())
AND P.Deleted IS NULL
AND (P.PaymentDue < C.CancelOn OR C.CancelOn IS NULL)
AND P.PurchaseAmount <> '0'
AND ( haspastdue IS NULL OR haspastdue = 0)
)A where rn=1
© www.soinside.com 2019 - 2024. All rights reserved.