SQL查询IF EXISTS

时间:2016-11-10 06:54:27

标签: sql-server

我想检查另一个表中存在的数据..

我的表结构

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可以有多个数据组合域)

表指标数据样本数据:

enter image description here

表DataFields示例数据:

enter image description here

我试过查询:

注意:我不会传递dataid,我只传递字段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时,我需要获取值与dataid的组合。

输出应该像这样返回:

enter image description here

请建议我如何实现这个

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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

        )