簡體   English   中英

在正確的位置添加 CASE 表達式?

[英]Adding CASE expression in the correct spot?

我想更改此查詢:

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...
)

以便 c.AccountB 顯示“X”,如果它是“Y”。 所以我想做類似的事情

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

除了我遇到一些數據(a.Category)來自表 a 的問題,並且表 a 中沒有等於“Y”的記錄,因此連接不會從表中獲取類別數據一個。 因此該字段為空白。 我試圖避免將其添加到該表中,而寧願更改查詢。 我怎樣才能做到這一點? 我認為可行的是:

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...
)

我在這里用星號將 CASE 表達式放在第 7 行 ***

這會返回完全相同的記錄嗎? 這是一個運行時間非常長且難以測試的查詢,因此我嘗試盡可能少地運行它,希望有一些輸入可以幫助我,因此這不會變成一個 6 小時的項目。

編輯:我有一個錯字,選擇的第一列應該引用第一個表 - 我改變了它(表“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 '會嘗試:

如果你只想 select 那么:

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
...

相反,如果您想將其用作聯接的一部分,則必須在聯接中使用它。 由於您沒有顯示“c”是如何連接的,也沒有顯示“c”和“a”是如何相關的,我將嘗試舉一個例子:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM