如何在SQL中按同一列过滤两次?
How to filter by the same column twice in SQL?
假设我有一列要求和的日期、类别和值。我希望按类别分组并对值求和,使其满足特定日期集的特定条件,以及另一组日期的另一个条件。
类似于:
SELECT categories, SUM(values)
FROM table
group by categories
having SUM(values) = 0 WHEN dates between w AND x
AND having SUM(values) > 10000 WHEN dates between y and z
谢谢!
我想你想要条件聚合:
select categories, sum(values)
from table
group by categories
having sum(case when dates between w and x then values else 0 end) = 0 and
sum(case when dates between y and z then values else 0 end) > 10000 ;
您可以执行以下操作(SUM
只有符合条件的值进入 IIF
子句):
SELECT categories, SUM(values)
FROM table
GROUP BY categories
HAVING SUM(IIF(dates BETWEEN w AND x, values, 0)) = 0
AND SUM(IIF(dates BETWEEN y AND z, values, 0)) > 10000
假设我有一列要求和的日期、类别和值。我希望按类别分组并对值求和,使其满足特定日期集的特定条件,以及另一组日期的另一个条件。
类似于:
SELECT categories, SUM(values)
FROM table
group by categories
having SUM(values) = 0 WHEN dates between w AND x
AND having SUM(values) > 10000 WHEN dates between y and z
谢谢!
我想你想要条件聚合:
select categories, sum(values)
from table
group by categories
having sum(case when dates between w and x then values else 0 end) = 0 and
sum(case when dates between y and z then values else 0 end) > 10000 ;
您可以执行以下操作(SUM
只有符合条件的值进入 IIF
子句):
SELECT categories, SUM(values)
FROM table
GROUP BY categories
HAVING SUM(IIF(dates BETWEEN w AND x, values, 0)) = 0
AND SUM(IIF(dates BETWEEN y AND z, values, 0)) > 10000