算不遵守where子句

时间:2016-07-01 08:24:48

标签: sql sql-server sql-server-2012

你好帮忙请混淆......

我有这个查询,假设只取出typei列的计数,但是当我运行它时,它会拉出整个数据库的计数,并且不遵守where子句规则......

SELECT [type], typei, vtdate, count (typei) as count
FROM vtindex
where typei is not null or typei <> '#'
and vtdate between '2016/06/01' and '2016/06/30'
GROUP BY
[type], Typei, vtdate
HAVING
COUNT(typei) > 1

这个想法是用户输入日期垃圾邮件,并为他们提供特定日期垃圾邮件的typei计数

感谢...

4 个答案:

答案 0 :(得分:2)

在GROUP BY - Clause中,只有你想要分组的列,而不是你要计算或总和的列。所以试试吧:

SELECT [type], vtdate, count(typei) as count
FROM vtindex
WHERE typei IS NOT NULL OR typei <> '#'
   and vtdate between '2016/06/01' and '2016/06/30'
GROUP BY [type], vtdate
HAVING count(typei) > 1

答案 1 :(得分:2)

添加括号以正确过滤记录。

目前,where子句按以下顺序验证

Where typei IS NOT NULL OR (typei <> '#'
  and vtdate between '2016/06/01' and '2016/06/30')

但你需要这个

Where (typei IS NOT NULL OR typei <> '#')
  and vtdate between '2016/06/01' and '2016/06/30'

答案 2 :(得分:1)

试试这个:

SELECT [type], typei, count (typei) as count
FROM vtindex
where typei is not null or typei <> '#'
and vtdate between '2016/06/01' and '2016/06/30'
GROUP BY
[type], Typei
HAVING
COUNT(typei) > 1

想法是删除除Typei之外的其他字段并按其分组。

祝你好运!

答案 3 :(得分:0)

我认为它应该是这样的;)

SELECT [type], typei, vtdate, count (typei) as count
FROM vtindex
where (typei is not null or typei <> '#')
and vtdate between '2016/06/01' and '2016/06/30'
GROUP BY
[type], Typei, vtdate
HAVING
COUNT(typei) > 1

如果没有这个括号,当typei不为空时,将不会计算其他条件。