2017-07-06 63 views
2

我有問題爲下表生成SQL查詢。 這裏是我的表:if else使用sql查詢

County   | Store  | Stock | Display | Designation 
--------------- | --------- | ----- | ------- | ------------ 
USA    | USD  | 1  | Yes  | Merchandiser 
USA    | USD  | 2  | Yes  | Promoter 

我想成爲導致這樣

County   | Store  | Stock | Display | Designation 
--------------- | --------- | ----- | ------- | ------------ 
USA    | USD  | 2  | Yes  | Merchandiser 
USA    | USD  | 2  | Yes  | Promoter 

的情況是,如果名稱是發起人,同時使用顯示器和庫存數據。 如果指定來自Merchandiser,則使用來自Promoter的庫存數據 如何實現此目的?

+1

這個問題並目前不符合StackOverflow規則。請說明迄今爲止您嘗試過的內容,以及其他一些示例,其中一些將會更改/更新,一些則不會。 – Reeza

+5

美國是一個國家,而不是一個縣。 – jarlh

+1

也許是一個自我離開的加入?添加更多樣本數據並調整預期結果,以使事情更清晰。 – jarlh

回答

2

請嘗試以下代碼來創建臨時表

--===== If the test table already exists, drop it 
IF OBJECT_ID('TestDB..#mytable','U') IS NOT NULL 
    DROP TABLE #mytable 
--===== Create the test table with 
CREATE TABLE #mytable 
     (
     Country varchar(20), 
     Store varchar(20), 
     Stock int, 
     Display varchar(5), 
     Designation varchar(20) 
     ) 
    --===== Insert the test data into the test table 
INSERT INTO #mytable 
     (Country, Store, Stock, Display, Designation) 


SELECT 'SG','a','2','YES','Merchandiser' UNION ALL 
SELECT 'SG','a','4','YES','Promoter' 

現在使用下面的上述查詢

SELECT Country, 
     Store , 
     (CASE WHEN (Designation = 'Merchandiser') THEN (SELECT SUM(STOCK) FROM #mytable WHERE Country = Country AND Designation = 'Promoter' GROUP BY Country) ELSE STOCK END) AS "stock", 
     Display, 
     Designation FROM #mytable 
2
Select a.Country, a.Store 
, Stock = CASE WHEN a.Designation = "Merchendiser" THEN b.Stock ELSE a.Stock 
, Display = CASE WHEN a.Designation = "Merchendiser" THEN b.Display ELSE a.Display 
, a.Designation 
FROM YourTable a LEFT JOIN YourTable b WHERE b.Designation = "Promoter" 

可能會伎倆。目前無法測試。編輯:我看到你沒有說明你使用了哪個SQL(即SQL服務器,MySQL,PostgreSQL等,因此取決於這個解決方案可能無法運行)。

+0

需要考慮什麼時候b爲空(即沒有啓動子) – JohnHC

2

嘗試這個

SELECT County, 
      Store , 
      (CASE WHEN (Designation = 'Merchandiser') THEN (SELECT SUM(STOCK) FROM TABLE WHERE County = County AND Designation = 'Promoter' GROUP BY County) ELSE STOCK END) AS "stock", 
      Display, 
      Designation 
FROM table 

這個請求給你所需要的結果。

+0

它是否工作? –

+0

OP將另一個A標記爲已接受。 – Sami

2

我想你期待這樣的查詢

 

    Select a.Country, a.Store 
    , (CASE WHEN a.Designation = "Merchendiser" THEN (select Top 1 b.Stock from YourTable b where b.Designation = "Promoter" and b.Country = a.Country and b.Store = a.Store order by id desc) ELSE a.Stock) as Stock 
    , a.Display 
    , a.Designation 
    FROM YourTable a WHERE b.Designation = "Promoter"