2016-11-10 130 views
0

我想檢查另一個表中的數據存在..SQL查詢IF EXISTS

我的表結構

CREATE TABLE [dbo].[IndicatorData] 
(
    [id] [bigint] IDENTITY(1,1) NOT NULL, 
    [value] [float] NOT NULL, 
    [indicatorId] [int] NOT NULL, 
    [source] [nvarchar](500) NOT NULL, 
    [uploaded] [bit] NOT NULL, 
    [createdBy] [nvarchar](500) NULL, 
    [createdOn] [datetime] NULL, 
    [lastModifiedBy] [nvarchar](500) NULL, 
    [lastModifiedOn] [datetime] NULL 
) 

表2

CREATE TABLE [dbo].[DataFields] 
(
    [dataId] [bigint] NOT NULL, 
    [fieldId] [int] NOT NULL 
) 

IndicatorData.idDataFields.dataid(關係IndicatorData.id能有多個數據字段的組合)

表IndicatorData樣本數據:

enter image description here

表數據域採樣數據:

enter image description here

查詢我的嘗試:

:我不會通過數據ID,我會只通過字段編號& indicatorid

方案1

SELECT * 
FROM IndicatorData a 
INNER JOIN DataFields b ON a.id = b.dataid 
WHERE a.indicatorid = 72 
    AND b.fieldid IN (59, 207) 

enter image description here

當我通過字段id,我需要得到與數據ID值的組合。

輸出應該返回這樣的:

enter image description here

請建議我如何能實現這一目標

+0

您的查詢看起來好像沒什麼問題 - 什麼是不工作? – cco

+0

你可以看到Scaneiro#1並比較輸出..你可以找到差異 –

+0

不太清楚你想要什麼,你的意思是你只想輸出具有相同值和多個記錄的id?即在場景1輸出中,id = 69137的記錄不是您想要的輸出內容? – jyao

回答

0

這是否對你的工作?

;with c as (
SELECT a.id, cnt = count(*) from IndicatorData a 
INNER JOIN DataFields b ON a.id=b.dataid 
where a.indicatorid = 72 and b.fieldid in(59,207) 
group by a.id 
having count(*) > 1 
) 
select a.*, b.* from IndicatorData a INNER JOIN DataFields b 
ON a.id=b.dataid 
inner join c 
on a.id = c.id; 
0

如果我理解正確的要求,可以爲以下:

SELECT * from 
    IndicatorData a INNER JOIN 
    DataFields b ON a.id=b.dataid 
WHERE 
    a.indicatorid = 72 AND 
    a.id IN 
     (
      SELECT df.id FROM DataFields df 
      WHERE df.fieldid IN (59,207) 
      GROUP BY df.dataId HAVING COUNT(1) > 1 

     )