简体   繁体   中英

Adding CASE expression in the correct spot?

I want to change this query:

select
   t.AccountA
   ,t.AccountB
   ,t.totalNumber
     ,a.Category
from TableA t
left join Accounts a
on t.ActNum = a.ActNum
left join
 (select distinct
             s.col1
  from (
            select ....

            from Table
            group by...
   ) st
   left join (select S....
                 group by..
                 ) g on...
   left join (select... on ...
   ) t on ...
where...
)

so that c.AccountB displays "X" if it was a "Y". So I want to do something like

CASE WHEN c.AccountB = 'Y' THEN 'X' ELSE 'c.AccountB END

Except I'm having a problem where some data (a.Category) is coming from the table a, and table a doesn't have a record in it equal to "Y", so the join doesn't get the category data from a. That field is therefore blank. I'm trying to avoid adding it to that table and would rather change the query. How can I do this? What I think would work is:

select
 t.AccountA
 ,t.AccountB
 ,t.totalNumber
 ,a.Category
from TableA t
left join ****** (Select CASE WHEN t.AccountB = 'Y' THEN 'X' ELSE 't.AccountB END Accounts a)
on t.ActNum = a.ActNum
left join

 (select distinct
         col1
from (
        select ....

        from Table
        group by...
 ) sta
left join (select S....
             group by..
             ) g on...
  left join (select... on ...
   ) t on ...
where...
)

Where I put the CASE expression in the 7th line here by the asterisks ***

Will this return exactly the same records? This is a really long running query and difficult to test so I'm trying to run it as few times as possible, would like some input to help me so this doesn't turn into a 6 hour project.

EDIT: I had a typo, the first colummns selected were supposed to reference the first table - I changed it (table "t")

First, this might be as simple as getting rid of the single quote before c.AccountB CASE WHEN c.AccountB = 'Y' THEN 'X' ELSE c.AccountB END Otherwise I'm not quite sure I understand what you want but I'll try:

If you just want to select then:

select
   c.AccountA
   ,CASE WHEN c.AccountB = 'Y' THEN 'X' ELSE c.AccountB END AccountB
   ,totalNumber
     ,a.Category
from TableA t
left join Accounts a
on t.ActNum = a.ActNum
left join
...

If instead you want to use this as part of a join you'll have to use it in your join. Since you don't show how "c" is joined, nor how "c" and "a" are related I will try to give an example:

select
 c.AccountA
 ,CASE WHEN c.AccountB = 'Y' THEN 'X' ELSE c.AccountB END AccountB
 ,totalNumber
 ,a.Category
from CheckRegister c
left join Accounts a
   on a.ActNum = c.AccountA
left join Accounts b
   on b.ActNum = CASE WHEN c.AccountB = 'Y' THEN 'X' ELSE c.AccountB END

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