访问所有记录的SQL查询(非零)

时间:2016-05-09 21:35:23

标签: sql ms-access

Date        Name    Charge
1/15/2015   Alpha   3.39
2/15/2015   Alpha   3.39
2/15/2015   Beta    3.39
2/15/2015   Gamma   2
3/15/2015   Gamma   3
3/15/2015   Alpha   5
4/15/2015   Beta    3.39

以上是Access中的示例表。我的目的是捕获所有对于' Charge'具有严格值3.39的唯一名称,但如果任何名称的值不是3.39,则查询将根本不返回名称。例如,基于样本数据,正确写入查询将仅导致" Beta"出现。

如何针对上述要求编写SQL查询?

2 个答案:

答案 0 :(得分:1)

select distinct Name from thisTable s1
left join
(select * from thisTable where Charge<>3.39) s2
on
s1.Name=s2.Name
where
s2.Name is null
and
s1.Charge=3.39

答案 1 :(得分:1)

嗯,我得到了答案,但是另一种方式:

SELECT [Name] FROM dbo.charges
WHERE [Charge] = '3.39'
GROUP BY [Name]
HAVING [Name] NOT IN (
    SELECT [Name] FROM dbo.charges
    WHERE [Charge] <> '3.39'
    GROUP BY [Name]
)

好的,那是SQL Server版本,这里的Access版本略有不同:

SELECT [Name] FROM charges
WHERE [Charge] = 3.39
GROUP BY [Name]
HAVING [Name] NOT IN (
    SELECT [Name] FROM charges
    WHERE [Charge] <> 3.39
    GROUP BY [Name]
)

这里的表名是&#34;费用&#34; - 将表格和字段名称更改为您的表格和字段名称,但根据上述对话,我不确定这是否是您所需要的。

以下是添加了参数的更新:

PARAMETERS [Start Date] DateTime, [End Date] DateTime; 
SELECT charges.Name
FROM charges
WHERE (((charges.Date)>=[Start Date] And (charges.Date)<=[End Date]) AND ((charges.Charge)=3.39))
GROUP BY charges.Name
HAVING (((charges.Name) Not In (SELECT [charges].[Name] FROM [charges] WHERE [charges].[Charge] <> 3.39 GROUP BY [charges].[Name])));