2012-05-31 59 views
2

我現在正在維護一個大應用程序,其他人寫了一些大型政府遺留系統的數據挖掘。基本上我需要一個單一的查詢結果來填充一個gridview,它從技術訂單中獲取每個零件編號並計算Fedlog表中的匹配零件編號。如果沒有找到,請查看「商業」表。現有的查詢目前只能看在Fedlog表,內容如下:是否有可能在一個表中存在「不在/存在」然後在另一個表中?

select p.*, 
(select case when count(*) > 0 then 'Y' else 'N' end as SL 
    from tbl_fedlog where [Part Number] = p.[Part Number]) as SL 
from tbl_pcms p 
where p.[Tech Order] = '0B-E0C-9' order by p.Figure, p.[Index], p.Indenture 

當「N」我得到了在商用表格看。我能否就這方面的最佳方式提出一些建議?

回答

1

'N'場景的結果應該是什麼樣子 - 只是另一個'Y'/'N'的答案?如果是這樣,您應該能夠簡單地用另一個標量查詢替換「N」表達式與「商業」表。

0

下面是一個Fedlog查詢和商業查詢,來在每一個生存之間的UNION ALL

SELECT p.* 
, SL = 'Y' 
, part_count = (SELECT COUNT(*) FROM tbl_fedlog WHERE [Part Number] = p.[Part Number]) 
from tbl_pcms p 
where p.[Tech Order] = '0B-E0C-9' 
AND EXISTS(SELECT 1 FROM tbl_fedlog WHERE [Part Number] = p.[Part Number]) 

UNION ALL 

SELECT p.* 
, SL = 'Y' 
, part_count = (SELECT COUNT(*) FROM tbl_commercial WHERE [Part Number] = p.[Part Number]) 
from tbl_pcms p 
where p.[Tech Order] = '0B-E0C-9' 
AND EXISTS(SELECT 1 FROM tbl_commercial WHERE [Part Number] = p.[Part Number]) 
AND NOT EXISTS(SELECT 1 FROM tbl_fedlog WHERE [Part Number] = p.[Part Number]) 

我需要更多的信息來解決對方的回答雖然提到「N」的情況。

+0

很好!非常感謝! – user1428940

+0

不客氣。請確保點擊答覆的複選標記接受:) –

0

如果邏輯是當在任一FedlogCommercial表和'N'存在否則部件,用於顯示'Y',則可以嘗試分組&分別聚集這些表和(outer-)加入聚合結果集來tbl_pcms,像這樣:

SELECT 
    p.*, 
    CASE WHEN COALESCE(f.PartCount, c.PartCount) IS NULL THEN 'N' ELSE 'Y' END AS SL 
FROM tbl_pcms p 

    LEFT JOIN (
    SELECT 
     [Part Number], 
     COUNT(*) AS PartCount 
    FROM tbl_fedlog 
    GROUP BY [Part Number] 
) f ON p.[Part Number] = f.[Part Number] 

    LEFT JOIN (
    SELECT 
     [Part Number], 
     COUNT(*) AS PartCount 
    FROM tbl_commercial 
    GROUP BY [Part Number] 
) c ON p.[Part Number] = c.[Part Number] 

WHERE p.[Tech Order] = '0B-E0C-9' 
ORDER BY 
    p.Figure, 
    p.[Index], 
    p.Indenture 
相關問題