SQL多条件用例出现问题 [英] SQL Multi Conditional CASE WHEN issues

查看:43
本文介绍了SQL多条件用例出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下情况下尝试使用CASE WHEN时遇到问题:

I am encountering a problem when trying to use a CASE WHEN for the following scenario:

我有一个表,其中有3列以上,但是这3列是唯一相关的:order_number,payment_method,order_date.

I have a table with more than 3 columns but these 3 are the only relevant ones: order_number, payment_method, order_date.

可以有多个订单"每个order_number.永远不会有两个相同的order_date

There can be multiple "orders" per order_number. There will never be two of the same order_date

<身体>
订单号付款方式订购日期
120 现金 01/01/2021
175 信用卡 01/02/2021
209 现金 01/03/2021
209 信用卡 01/04/2021
209 个人支票 01/05/2021
209 信用卡 01/06/2021
209 现金 01/07/2021
209 个人支票 01/08/2021
277 信用卡 01/09/2021
301 现金 01/10/2021
333 个人支票 01/11/2021
333 现金 01/12/2021
333 现金 01/13/2021
333 个人支票 01/14/2021
400 信用卡 01/15/2021
551 信用卡 01/16/2021
551 现金 01/17/2021
680 个人支票 01/18/2021

我正在尝试将其合并,以便基于以下逻辑,每个订单号仅包含1行的列表:

I am trying to consolidate it so that I have a list with only 1 row per order number, based on the following logic:

  1. 如果只有一个订单号-请返回订单日期
  2. 如果有> 1个相似的订单号,并且其中任何一个订单都是使用信用卡付款的,请返回使用信用卡付款的最新订单日期
  3. 如果相似的订单号大于&> 1,并且没有使用信用卡付款的订单,请返回最近的订单日期.

目标看起来像这样:

<身体>
订单号付款方式订购日期
120 现金 01/01/2021
175 信用卡 01/02/2021
209 信用卡 01/06/2021
277 信用卡 01/09/2021
301 现金 01/10/2021
333 个人支票 01/14/2021
400 信用卡 01/15/2021
551 信用卡 01/16/2021
680 个人支票 01/18/2021

没有重复的订单号,并且当有重复的订单号时,将遵循逻辑并拉出该行.

No duplicate order numbers, and when there were duplicate order numbers, the logic was followed and that row was pulled.

我尝试了CASE WHEN的各种方法,但是在THEN部分上应用条件时总是失败.

I tried various methods of CASE WHEN, but always fail when it comes to applying a condition on the THEN part.

推荐答案

作为一般方法,您可以使用 row_number():

As a general method, you can use row_number():

select o.*
from (select o.*,
             row_number() over (partition by order_number
                                order by (case when payment_method = 'Credit Card' then 1 else 2 end),
                                         order_date desc
                               ) as seqnum
      from orders o
     ) o
where seqnum = 1;

这是通用SQL,可以在任何数据库中使用.但是,取决于您的数据库,可能会有快捷方式.

This is generic SQL and should work in any database. However, depending on your database there might be shortcuts.

这篇关于SQL多条件用例出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆