如何从具有条件的条件中排除日期?

时间:2019-05-06 09:30:48

标签: sql sql-server count

我正在编写查询以对日期在...201801之间的变量进行计数,并且我想排除日期为201812的变量。我该如何实现?

这是我到目前为止所做的:

201806

4 个答案:

答案 0 :(得分:1)

在您的条件中添加Var_Date not in (201806)

SELECT COUNT (Var1) as 'varCount' 
from Vartable inner join UserTable on usr_id 
where usr_login = 'bella' 
  and Var_Date between 201801 and 201812 
  and Var_Date not in (201806)

答案 1 :(得分:1)

如果您的日期存储为日期,则比较也应为日期。我建议:

select count(Var1) as varCount 
from Vartable inner join
     UserTable
     on usr_id 
where usr_login = 'bella' and
      (var_date >= '20180101' and var_date < '20180601' or
       var_date >= '20180701' and var_date < '20190101'
      )

如果您正在调用的列var_date实际上是代表一个月的整数,那么我建议重命名它。然后您可以简单地做到:

where usr_login = 'bella' and
      yyyymm >= 201801 and
      yyyymm <= 201812 and
      yyyymm <> 201806

答案 2 :(得分:0)

只需将201806子句中的WHERE排除为

WITH CTE AS
(
  SELECT 201801 Var_Date 
  UNION
  SELECT 201802
  UNION
  SELECT 201803
  UNION
  SELECT 201804
  UNION
  SELECT 201805
  UNION
  SELECT 201806
  UNION
  SELECT 201807
  UNION
  SELECT 201808
  UNION
  SELECT 201809
  UNION
  SELECT 201810
  UNION
  SELECT 201811
  UNION
  SELECT 201812
  UNION
  SELECT 201901
  UNION
  SELECT 201902
)

SELECT COUNT(1) Cnt
FROM CTE
WHERE Var_Date BETWEEN 201801 AND 201812
      AND Var_Date != 201806;

如果该列为DATE,那么您可以这样做

SELECT COUNT(Var1) VarCount
FROM VarTable V INNER JOIN UserTable U
ON V.UserId = U.UserId --Don't forget the JOIN conditions
WHERE U.Usr_Login = 'bella'
      AND
      Var_Date BETWEEN '2018-01-01' AND '2018-12-31'
      AND
      Var_Date NOT BETWEEN '2018-06-01' AND '2018-06-30'

您还可以将MONTH()YEAR()用作

SELECT COUNT(Var1) VarCount
FROM VarTable V INNER JOIN UserTable U
ON V.UserId = U.UserId --Don't forget the JOIN conditions
WHERE U.Usr_Login = 'bella'
      AND
      MONTH(Var_Date) <> 6
      AND
      YEAR(Var_Date) = 2018;

答案 3 :(得分:0)

SELECT COUNT(Var1) as 'varCount' 
from Vartable 
inner join UserTable on usr_id 
where usr_login = 'bella' 
  and Var_Date between '201801' and '201812'
  and Var_Date <> '201806'