2013-05-02 44 views
0

我正在嘗試在類型不是上訴的表中找到所有的yearcaseseqnumbers表1.錯誤來源於表中有多行的yearcaseseqnumber。這是我所嘗試過的:Exists SQL Statement

Select caseseqnumber, year 
from caseparticipants 
where not exists (Select * 
        from caseparticipants 
        where participanttype = 'Appellant Rep 1') 

任何幫助?

+2

你說「錯誤即將到來」會發生什麼?你有沒有收到實際的錯誤信息?如果有,請告訴我們哪一個。或者只描述發生了什麼(或不發生)。 – APC 2013-05-02 12:16:10

+0

我沒有收到錯誤信息,我只是沒有結果 – parkjohnston 2013-05-02 12:27:05

回答

0

您可以加入caseparticipants與本身,使用LEFT JOIN。如果連接成功好好嘗試一下,這意味着caseseqnumber和年沒有與participanttype = 'Appellant Rep 1'行:

SELECT 
    c1.caseseqnumber, 
    c1.year 
FROM 
    caseparticipants c1 LEFT JOIN caseparticipants c2 
    ON c1.year=c2.year AND c1.caseseqnumber=c2.caseseqnumber 
    AND c2.participanttype = 'Appellant Rep 1' 
WHERE 
    c2.year IS NULL 

編輯

比較caseseqnumber,一年的不同組合的數目,和如果你想有一個上訴人而不是代表所有的情況下

SELECT 
    COUNT(DISTINCT 
    CAST(c1.caseseqnumber AS VARCHAR) + '-' + CAST(c1.year AS VARCHAR)), 
    COUNT(DISTINCT 
    CAST(c2.caseseqnumber AS VARCHAR) + '-' + CAST(c2.year AS VARCHAR)) 
FROM 
    caseparticipants c1 LEFT JOIN caseparticipants c2 
    ON c1.year=c2.year AND c1.caseseqnumber=c2.caseseqnumber 
    AND c2.participanttype = 'Appellant Rep 1' 
+0

增加到這是有辦法比較不同年份和案例數量的總數與這些結果來獲得一個pecentage? – parkjohnston 2013-05-02 12:36:29

+0

@parkjohnston我已經更新了我的答案,我希望這是你正在尋找的! – fthiella 2013-05-02 12:53:47

+0

Msg 102,Level 15,State 1,Line 2 ','附近的語法不正確。是我得到的錯誤。還有沒有一種方法可以獲得所有病例數和年數的總數?我試圖比較他們得到一個百分比。 – parkjohnston 2013-05-02 12:54:52

1
Select 
    caseseqnumber, 
    year 
from 
    caseparticipants 
where 
    participanttype != 'Appellant Rep 1' 
+0

這不起作用,因爲也有條款只是上訴人,他們可能在不同的線路上。我期望找到只有上訴人而非代表人的案件。 – parkjohnston 2013-05-02 12:19:38

0

爲什麼不嘗試在主查詢中直接使用WHERE條件而不是使用子查詢?

SELECT caseseqnumber, year 
    FROM caseparticipants 
WHERE participanttype != 'Appellant Rep 1' 
+0

這不起作用,因爲也有條款只是上訴人,他們可能在不同的線路上。我期待找到只有上訴人而不是代理人的案件 – parkjohnston 2013-05-02 12:20:07

+1

@parkjohnston - 您能否展示您的確切數據結構和要求? – hims056 2013-05-02 12:21:22

+0

https://docs.google.com/document/d/1LI0XudmDJ1TT4c6yBjMhPioFlgGcqL1GYw8kYYvOFHo/edit?usp=sharing – parkjohnston 2013-05-02 12:25:23

2

爲什麼你需要在那裏做一個嵌套搜索。僅在需要檢查多個 數據庫 表中的情況下才需要嵌套搜索。

堅持

select caseqnumber,year from caseparticipants where paticipanttype <> 'Appellant Rep 1' 

(<>是不等於SQL子句)

+3

_只需要在多個數據庫中檢查事件時需要嵌套搜索._謹慎解釋該陳述? – Taryn 2013-05-02 12:18:31

+0

這不起作用,因爲也有隻是上訴人的條目,他們可能在不同的線路上。我正在尋找只有案件有上訴人,而不是一個代表 – parkjohnston 2013-05-02 12:21:38

+0

我覺得他們需要在這種情況下,就好像我只是要求一個線,其中入口不是上訴代表1 ..我可能會得到另一行上訴人和上訴人代表的案件編號和年份存儲在兩個不同的行上 – parkjohnston 2013-05-02 12:23:07

0

01有AA型的「上訴人衆議員1」的組合的數量,你可以使用這個SQL Server查詢
Select caseseqnumber, year 
from caseparticipants cp1 
where not exists (Select null 
        from caseparticipants cp2 
        where cp2.participanttype = 'Appellant Rep 1' 
        and cp1.caseseqnumber = cp2.caseseqnumber 
        and cp1.year = cp2.year 
)