Domanda

I'm doing some data conversion and I'm required to group my data and perform some logical code on each group. For the example below, I want to group by customer name and customer ID and anytime this group contains the source system as SAP, i want to survive that row and not the others. I've been playing around with row_number() over partition by to group my data but I'm finding it difficult to do what I need to do unless I can run some logic on a group basis. Any help would be greatly appreciated!

Source System    Customer_ID  Customer_Name Survivor 
------------------------------------------------------ 
SAP              1               Walmart         Y  
Oracle           1               Walmart         N  
Oracle           1               Walmart         N  
Oracle           1               Walmart         N  
Oracle           2               Target          Y  
Oracle           2               Target          N  
Oracle           2               Target          N
È stato utile?

Soluzione

The following matches your expected output for survivor, but I am not sure of your logic for customer 2 as all rows seem the same:

SELECT  "Source System",
        "Customer ID",
        "Customer Name",
        CASE WHEN ROW_NUMBER() OVER(PARTITION BY "Customer ID" 
                                    ORDER BY CASE WHEN "Source System" = 'SAP' 
                                                THEN 0 
                                                ELSE 1 
                                            END)
                             = 1 THEN 'Y' ELSE 'N' END AS "Survivor"
FROM    T

Example on SQL Fiddle

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top