Case when over partition

Bone_12 361 Reputation points
2022-07-19T13:10:25.85+00:00

Hi,
I have the following logic below that doesn't work as I would have hoped/expected.

Here's the statement:

Select
Apps.name,
substring(apps.code,3,7),

Max(case when comp.id = 1 and comp.val = 1 then comp.desc else substring(apps.code,3,7) end) over (partition by substring(apps.code,3,7)) as cust_id

From
Dbo.apps
Left join dbo.comps
On apps.id = comps.id

The reason that it doesn't work is that I get exactly the same values as the column substring(apps.code,3,7) and I should be expecting a combination of the two.

Is there something wrong with my case statement please?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,273 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,516 questions
{count} votes

2 answers

Sort by: Most helpful
  1. LiHong-MSFT 10,036 Reputation points
    2022-07-20T03:57:20.107+00:00

    Hi @Bone_12

    I get exactly the same values as the column substring(apps.code,3,7)

    With this OVER clause over (partition by substring(apps.code,3,7)), you will always get the same Max Value.
    Here is my guess based on your description, if it doesn't work, please provide more details including some sample data and your desired output.

    Select Apps.name  
          ,substring(apps.code,3,7)  
          ,Max(case when comp.id = 1 and comp.val = 1 then comp.desc else substring(apps.code,3,7) end)as cust_id  
    From Dbo.apps Left join dbo.comps On apps.id = comps.id  
    Group by Apps.name,substring(apps.code,3,7)  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Olaf Helper 38,941 Reputation points
    2022-07-20T05:43:14.067+00:00

    Is there something wrong with my case statement please?

    We can't say, because we don't have your data and we don't know which result you expect.
    Please post table design as DDL, some sample data as DML statement and the expected result.

    0 comments No comments