2016-11-10 133 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 

     )