SQL Server Displaying 'Working on it' for duplicate Item numbers

mrphzbgm  于 2023-06-04  发布在  其他
关注(0)|答案(2)|浏览(127)
ItemStatus
7080On Hold
7080Working on It
7090On Hold

When Item has same number i.e 7080 and has 'working on it' and 'hold' status, it should show 'Working on it' on both the status.

I wrote a solution, using a case expression, but did not work.

Edit: adaptation of @lemon's answer to my data.

SELECT DISTINCT 
    SUBSTRING(item, 1, 4) Item,
    CASE 
        WHEN MAX(CASE 
                     WHEN [Eng Status] = 'Working on It' 
                         THEN 1 
                 END) OVER (PARTITION BY Item) = 1
            THEN 'Working on It'
            ELSE [Eng Status]
    END AS Status
FROM 
    tbl

Same result as previous, still not working.

ItemStatus
7080On Hold
7080Working on It
7090On Hold

Edit:

select col1,col2 from tbl

This is the data

abithluo

abithluo1#

You can use a CASE expression to assign 'Working on It' to all those records that have at least one of that status "MAX(Status='Working') = 1" for each "Item".

SELECT Item,
       CASE WHEN MAX(CASE WHEN Status='Working on It' THEN 1 END) OVER(PARTITION BY Item)=1
            THEN 'Working on It'
            ELSE Status
       END AS Status
FROM tab

If you're using SUBSTRING(item, 1, 4) instead of Item , you also need OVER(PARTITION BY SUBSTRING(item, 1, 4)) .

nx7onnlm

nx7onnlm2#

It is a bad idea to use the same name for an expression as for the original column. You call your expression item , but it is actually just a substring of the original item . This confused you and you partitioned your MAX OVER by item . The DBMS doesn't yet see the alias you created and assumes the column. Here is the corrected query:

SELECT DISTINCT 
    SUBSTRING(item, 1, 4) AS item,
    CASE 
        WHEN MAX(CASE 
                     WHEN [Eng Status] = 'Working on It' 
                         THEN 1 
                 END) OVER (PARTITION BY SUBSTRING(item, 1, 4)) = 1
            THEN 'Working on It'
            ELSE [Eng Status]
    END AS Status
FROM 
    tbl

相关问题