查询基于两个参数查找特定值

时间:2018-01-11 03:38:07

标签: sql sql-server

+----------+---------+---------+
| Column1  | Column2 | Column3 |
+----------+---------+---------+
|    1234. |    234. | No      |
|    1234. |    456. | Yes     |
|    1234. |    789. | No      |
|    3214. |    123. | No      |
|    3214. |    345. | No      |
|    3214. |    679. | No      |
+----------+---------+---------+

第1列有主要ID,其中有第2列中的某些子ID,我需要查找每个主要ID在第3列中是否至少有一个yes值。或者找到没有任何yes值的主要ID。

4 个答案:

答案 0 :(得分:2)

简单select查询应该适用于您的案例

select distinct Column1 
from yourtable
group by Column1 
having count(case when Column3 = 'Yes' then 1 end) > 0 
    or count(case when Column3 <> 'Yes' then 1 end) = count(*)

答案 1 :(得分:0)

尝试以下:

select distinct Column1 
from yourtable
where Column3 = 'Yes'
union
select distinct Column1 
from yourtable
where Column3 = 'No'

答案 2 :(得分:0)

根据您的问题评论和最近的评论,我认为以下3个结果可以解决您的问题(包括重现示例表的代码)。

CREATE TABLE [dbo].[tableName](
    [MainID] [VARCHAR] (10) NULL,
    [SubID] [VARCHAR] (10) CONSTRAINT pk_tableName_sid PRIMARY KEY,
    [Column3] [VARCHAR] (10) NULL
) ON [PRIMARY]
GO

INSERT INTO [dbo].[tableName]
SELECT '1234.','234.','No' UNION ALL
SELECT '1234.','456.','Yes' UNION ALL
SELECT '1234.','789.','No' UNION ALL
SELECT '3214.','123.','No' UNION ALL
SELECT '3214.','345.','No' UNION ALL
SELECT '3214.','679.','No' 
GO

--verify table data
--SELECT * FROM [dbo].[tableName]

--Per your Question: "I need to find if each main id has at least one yes value in column 3"
SELECT DISTINCT [MainID] AS 'MainIDs with at least one yes'
FROM [dbo].[tableName]
WHERE Column3 = 'Yes'

--Per your Question: "Or find main ids without any yes value."
SELECT DISTINCT [MainID] AS 'MainIDs without any yes value'
FROM [dbo].[tableName] 
WHERE [MainID] NOT IN (SELECT [MainID] FROM [dbo].[tableName] WHERE [Column3] = 'Yes')

--Per your comment: "so i need the data where the data needs to be in this format(1234. 456. Yes)"
SELECT DISTINCT '(' + [MainID] + ' ' + [SubID] + ' ' + [Column3] + ')' AS 'where the data needs to be in this format'
FROM [dbo].[tableName]
WHERE Column3 = 'Yes'

Results

第一个结果集标识具有相应MainID值的'Yes'

第二个结果集只标识那些没有相应MainID值的'Yes'

第三个结果集基于您的评论,以非常特定的格式请求数据。

示例,如果您想自己运行它:http://rextester.com/NUCF30131

答案 3 :(得分:0)

SELECT * FROM table
WHERE column3=yes;

同样没有

SELECT * FROM table
WHERE column3=no;

如果你想要合并,那么在查询之间使用UNION