简体   繁体   中英

How to avoid duplicates with case statement

I have a table with the following structure (customer id and product):

我的表

I'm trying to pivot the same, in order to have just one line per Id. To do this, I'm using case statements:

select distinct
id,
case when purchased_item = 'Item 1' then 'Y' else 'N' end item_1,
case when purchased_item = 'Item 2' then 'Y' else 'N' end item_2,
case when purchased_item = 'Item 3' then 'Y' else 'N' end item_3
from my_table

However, this is the result I get:

查询结果

Is there any way to get the same result but with just one single line per Id?

to answer your problem, you need to group by and use max fucntion:

select 
  id,
  max(case when purchased_item = 'Item 1' then 1 else 0 end) item_1,
  max(case when purchased_item = 'Item 2' then 1 else 0 end) item_2,
  max(case when purchased_item = 'Item 3' then 1 else 0 end) item_3
from my_table
group by id

Starting with Oracle 11.1, you can use the pivot operator, as demonstrated below. Notice the additional samples I added in the with clause (which is there for testing only - remove it, and use your actual table and column names in the query). I added an id for a customer that only purchased Item 5 , which you don't seem to care about in the output, and another where a customer bought the same item more than once (assuming the "distinct" in your attempt was there for a reason).

with
  my_table(id, purchased_item) as (
    select 123, 'Item 1' from dual union all
    select 123, 'Item 2' from dual union all
    select 123, 'Item 3' from dual union all
    select 456, 'Item 1' from dual union all
    select 456, 'Item 2' from dual union all
    select 789, 'Item 1' from dual union all
    select 111, 'Item 5' from dual union all
    select 333, 'Item 1' from dual union all
    select 333, 'Item 1' from dual
  )
select id, nvl(i1, 'N') item_1, nvl(i2, 'N') item_2, nvl(i3, 'N') item_3
from   my_table
pivot  (max('Y') for purchased_item in ('Item 1' i1, 'Item 2' i2, 'Item 3' i3))
order  by id        -- IF NEEDED
;

 ID   ITEM_1   ITEM_2   ITEM_3
---   ------   ------   ------
111   N        N        N     
123   Y        Y        Y     
333   Y        N        N     
456   Y        Y        N     
789   Y        N        N  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM