筛选并执行多项计算

Filter and perform multiple calculations

我有一个数据集,我想使用 SQL 服务器对两个不同的查询进行分组、过滤和求和。

数据

name    stack   life    date        avail
aa      unused  remove  9/1/2021    5
aa      hi      keep    9/1/2021    1
aa      hey     stay    9/1/2021    1
aa      hey     fix     9/1/2021    2
aa      hey     keep    9/1/2021    4
aa      hi      no      9/1/2021    1
aa      hi      fix     9/1/2021    1
bb      ok      fix     9/1/2021    1
bb      yes     remove  9/1/2021    1
bb      ok      keep    9/1/2021    1
bb      ok      fix     9/1/2021    1
bb      ok      yes     9/1/2021    3
bb      unused  remove  9/1/2021    3
bb      ok      keep    10/1/2021   1

需要 (逻辑)

  1. 按名称分组并过滤到 2021 年 9 月 1 日
  2. WHERE 堆栈 != 'unused'
  3. 生活在'keep'和'stay'

+

  1. 按名称分组并过滤到 2021 年 9 月 1 日
  2. WHERE 堆栈 != 'unused'
  3. 以及生活在'keep'
  4. 汇总效用列

输出应该是:

name   date            sum_avail
aa     9/1/2021        11
bb     9/1/2021        2

我试过的:

SELECT name, date, SUM(avail) AS sum_avail   
FROM table
(WHERE stack NOT LIKE 'unused' AND WHERE life IN ('keep','stay') AND WHERE date == '9/1/2021')
+
(WHERE stack NOT LIKE 'unused' AND WHERE life IN ('keep') AND WHERE date == '9/1/2021')
GROUP BY name

任何建议都有帮助。

您可以使用 select case statement 来实现。

select [name], sum(case when life in ('keep','stay') then avail else 0 end) + 
     sum(case when life in ('keep') then avail else 0 end)
from test
where date = '9/1/2021' and  stack!='unused'
group by [name]

查看 dbfiddle http://sqlfiddle.com/#!18/6895b/26

SELECT name,date, SUM(avail) sum_avail FROM 
(SELECT * from Table_1 WHERE  stack != 'unused' AND life IN ('keep','stay') AND date='2021-09-01'
UNION ALL
SELECT * from Table_1 WHERE  stack != 'unused' AND life IN ('keep') AND date='2021-09-01') A
GROUP BY name, date

根据逻辑,将单个 SUM() 与多个 case 表达式结合使用。作为按单个日期搜索,然后使用 MAX() 作为日期,但如果需要日期范围搜索,则使用日期列 select 和按部分分组。

-- SQL Server (v2017)
SELECT name, MAX(date) "date"
     , SUM(CASE WHEN life IN ('keep','stay') THEN avail ELSE 0 END
           +
           CASE WHEN life = 'keep' THEN avail ELSE 0 END) sum_avail
FROM test_tbl
WHERE date = '9/1/2021'
    AND stack != 'unused'
GROUP BY name;

请检查 url https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=98f4dcee17dfe8c54edf7ab3e6fed561

SELECT [name]
      ,[date]
      ,SUM(avail) as sum_avail FROM 
(SELECT * from Test WHERE life IN ('keep','stay')
UNION ALL
SELECT * from Test WHERE life IN ('keep') ) as Test1 
WHERE  stack != 'unused' AND date='2021-01-09'
GROUP BY [name],[date]