2012-10-16 48 views
0

我試圖從兩個表創建一個查詢。SQL SELECT DISTINCT拼圖

如果您喜歡類別,並且「文檔」包含有關文檔本身的詳細信息,第一個表格是'文檔類型',第二個'文檔'文檔類型是。它們是相關的(即'文檔'包含與'文檔類型'的關鍵字段有關的字段)。

簡化,表如下所示: -

Document Type 
============= 
TypeID 
TypeName 
TypeDescription 


Document 
======== 
DocumentID 
DocumentType (fk of TypeID) 
DocumentRequired 

我跑的查詢需要的文檔類型的DISTINCT名單 - 這是第一個和最簡單的一點。

我想要做的是向查詢添加一列,然後查看'文檔',如果有任何相關文檔'DocumentRequired'等於TRUE,則顯示TRUE /是值。如果不是,則顯示FALSE/No。

我試過創建一個連接,但顯然如果有任何包含必需/非必需文檔的類別,我會得到重複。我想要的是一個是/否的標誌。

有人可以幫忙嗎?

+0

請出示你的現有代碼,即使它不工作。那麼有人會更容易回答你的問題。他們可以修復它,而不必從頭開始。 – dan1111

+0

如果您同時擁有TRUE和FALSE,您希望查詢做什麼? – Gidil

+0

如果它發現真假,那麼我希望它顯示爲真。最後一欄的基本要點是說該類別中有沒有標記爲DocumentRequired = true的文檔。 –

回答

1
SELECT dt.TypeID,dt.TypeName,dt.TypeDescription, 
    CASE 
     WHEN sum(CONVERT(int,ISNULL(d.DocumentRequired,0)))=0 THEN 'False/No' 
     ELSE 'True/Yes' 
    END [Any required documents] 
FROM DocumentType dt 
LEFT JOIN Document d on dt.DocumentType=dt.TypeID --terrible naming convention.... 
group by dt.TypeID,dt.TypeName,dt.TypeDescription 
+0

INNER JOIN錯誤,因爲此查詢將刪除沒有文檔的所有文檔類型 – Tobsey

+0

更改爲左連接 – UnhandledExcepSean

0
Select DISTINCT TypeID, 
       TypeName, 
       TypeDescription, 
       CASE WHEN 
        (select count(*) 
          from Document 
          where document.DocumentType = DocumentType.TypeID 
          and DocumentRequired = 'TRUE' 
        )>0 
        THEN 'YES' 
        ELSE 'NO' 
       END AS myYesNoField 
    FROM DocumentType 
0
SELECT 
    TypeID, 
    TypeName, 
    TypeDescription, 
    CASE WHEN NumRequiredDocuments > 0 THEN 'Yes' ELSE 'No' END RequiredDocumentsExist 
FROM 
(
    SELECT 
     DocumentType.TypeID, 
     DocumentType.TypeName, 
     DocumentType.TypeDescription, 
     SUM (CASE WHEN Document.Required <> 0 THEN 1 ELSE 0 END) NumRequiredDocuments 
    FROM 
     DocumentType 
     LEFT JOIN Document ON DocumentType.TypeID = Document.DocumentType 
) 
GROUP BY 
    TypeID, 
    TypeName, 
    TypeDescription 
0

鑑於你的表以下記錄: DocumentType

TypeID TypeName TypeDescription 
1 Type1 1st Type 
2 Type2 2nd Type 
3 Type 3 3rd Type 

文件

DocumentId DocumentType DocumentRequired 
1  1  0 
2  1  1 
3  2  0 
4  3  1 

然後follwoing選擇會得到你想要的東西:

SELECT TypeID, 
     TypeName, 
     TypeDescription, 
     CASE 
      WHEN EXISTS 
       (SELECT * 
       FROM Document 
       WHERE Document.DocumentType = TypeID 
        AND DocumentRequired = 1) THEN 'True' 
      ELSE 'False' 
     END AS DocumentRequired 
FROM DocumentType