2015-02-12 71 views
0

我想知道我怎麼能有一羣人最初選擇中編寫一個SQL腳本,這樣一:SQL查詢 - 確定誰只有一個禮物記錄

SELECT [RECORDS].[CONSTITUENT_ID] 
    ,[RECORDS].[FIRST_NAME] 
    ,[RECORDS].[LAST_NAME] 
    ,[DATEADDED] 
    ,[DTE] 
    ,[Amount] 
    ,[REF] 
    ,[TYPE] 
FROM [re7].[dbo].[GIFT] 
INNER JOIN [re7].[dbo].[RECORDS] 
ON GIFT.CONSTIT_ID LIKE RECORDS.ID 
WHERE ([DTE] BETWEEN '2/7/2015' AND '2/8/2015') 
ORDER BY [DATEADDED] DESC 

只選擇個人誰是「第一時間捐助者」(或誰只有一個禮物[RE7] [DBO]。[禮物]。

[RECORDS]是所有成分表。

[禮物]是所有的表錄音禮品

上述查詢的輸出,僅僅是一個表: CONSTITUENT_ID,名字,姓氏,DATEADDED,DTE,金額,樓盤,TYPE

我非常希望看到相同的輸出格式,但我想在[re7]中查詢僅選擇只有1個GIFT(按他們的記錄ID)的CONSTITUENT_ID [dbo]。[GIFT]。

對於缺乏顯示的數據,我表示歉意。我希望我可以更好地描述....

+0

你能提供一些示例數據和預期的結果。 – 2015-02-12 00:40:44

+0

你爲什麼要用這種方式使用'ON GIFT.CONSTIT_ID LIKE RECORDS.ID'? – 2015-02-12 01:28:28

回答

1
SELECT [RECORDS].[CONSTITUENT_ID] 
    ,[RECORDS].[FIRST_NAME] 
    ,[RECORDS].[LAST_NAME] 
    ,[DATEADDED] 
    ,[DTE] 
    ,[Amount] 
    ,[REF] 
    ,[TYPE] 
FROM [re7].[dbo].[GIFT] 
INNER JOIN [re7].[dbo].[RECORDS] 
ON GIFT.CONSTIT_ID LIKE RECORDS.ID 
WHERE ([DTE] BETWEEN '2/7/2015' AND '2/8/2015') 
    AND GIFT.CONSTIT_ID IN (
     SELECT CONSTIT_ID FROM re7.dbo.Gift GROUP BY CONSTIT_ID HAVING COUNT(*) = 1 
    ) /* another option is to add a subquery to the query you already had */ 
ORDER BY [DATEADDED] DESC 
+0

這與其他答案基本相同。但是,將其併入現有查詢稍微容易一些。 – shawnt00 2015-02-12 01:39:37

0

該解決方案只是簡單地選擇所有隻做過一次捐贈並隨後加入的成分,從而限制了結果集。

SELECT 
    r.[CONSTITUENT_ID] 
    ,r.[FIRST_NAME] 
    ,r.[LAST_NAME] 
    ,[DATEADDED] 
    ,[DTE] 
    ,[Amount] 
    ,[REF] 
    ,[TYPE] 
FROM 
    (select [CONSTIT_ID] from [re7].[dbo].[GIFT] group by [CONSTIT_ID] having count([CONSTIT_ID]) = 1) g1 
    inner join [re7].[dbo].[GIFT] g 
     on g.[CONSTIT_ID] = g1.[CONSTIT_ID] 
    INNER JOIN [re7].[dbo].[RECORDS] r 
     ON g.CONSTIT_ID LIKE r.RECORDS.ID 
WHERE ([DTE] BETWEEN '2/7/2015' AND '2/8/2015') 
ORDER BY [DATEADDED] DESC