SQLite 中的总计列

问题描述 投票:0回答:1

SQL 新手。 真的新...

以下代码产生所需的(且正确的)输出:

SELECT
  SUM (CASE WHEN Total < 2.00 THEN 1 ELSE 0 END) AS 'A',
  SUM (CASE WHEN Total BETWEEN 2.00 and 6.99 THEN 1 ELSE 0 END) AS 'B',
  SUM (CASE WHEN Total BETWEEN 7.00 AND 15.00 THEN 1 ELSE 0 END) AS 'C',
  SUM (CASE WHEN Total > 15.00 THEN 1 ELSE 0 END) AS 'D'
FROM
 invoices
ORDER BY
 BillingCity;
 A   B   C   D
170 120 111 11

我想添加“E”列,其中应包含总计 (412)。

不知道该怎么做。 是的,我用谷歌搜索过。 在这里看到了一些帖子,但没有任何内容符合我的要求。

sqlite sum
1个回答
0
投票

我怀疑您正在寻找一个总计为 A + B + C + D 的解决方案。这可能类似于...

with sub_totals as (
  SELECT
  SUM (CASE WHEN Total < 2.00 THEN 1 ELSE 0 END) AS 'A',
  SUM (CASE WHEN Total BETWEEN 2.00 and 6.99 THEN 1 ELSE 0 END) AS 'B',
  SUM (CASE WHEN Total BETWEEN 7.00 AND 15.00 THEN 1 ELSE 0 END) AS 'C',
  SUM (CASE WHEN Total > 15.00 THEN 1 ELSE 0 END) AS 'D'
FROM
 invoices
)
select 
  A, B, C, D, 
  A + B + C + D as 'E'
from sub_totals

但是,您的总范围(几乎)涵盖了

Total
的所有可能值。也就是说,E 只是行数:
count as 'E'

SELECT
  SUM (CASE WHEN Total < 2.00 THEN 1 ELSE 0 END) AS 'A',
  SUM (CASE WHEN Total BETWEEN 2.00 and 6.99 THEN 1 ELSE 0 END) AS 'B',
  SUM (CASE WHEN Total BETWEEN 7.00 AND 15.00 THEN 1 ELSE 0 END) AS 'C',
  SUM (CASE WHEN Total > 15.00 THEN 1 ELSE 0 END) AS 'D',
  count() as 'E'
FROM
 invoices

我说过你几乎涵盖了 Total 的所有可能值,但有一个微妙的错误。例如,总计 6.995 将不会被计算在内。

SELECT
  -- Up to, but not including, 2. Or [,2)
  SUM (CASE WHEN Total < 2.00 THEN 1 ELSE 0 END) AS 'A',
  -- From 2 up to 6.99. Or [2,6.99]
  SUM (CASE WHEN Total BETWEEN 2.00 and 6.99 THEN 1 ELSE 0 END) AS 'B',
  -- From 7 up to 15. Or [7,15]
  SUM (CASE WHEN Total BETWEEN 7.00 AND 15.00 THEN 1 ELSE 0 END) AS 'C',
  -- From, but not including, 15. Or (15,]
  SUM (CASE WHEN Total > 15.00 THEN 1 ELSE 0 END) AS 'D',

这是

between
的常见问题。为了做到这一点,您需要混合使用包含和排他边界。通常,您需要一个包含的下限和一个排除的上限。 有时会写成
[x,y)

SELECT
  -- Up to, but not including, 2. Or [,2)
  SUM (CASE WHEN Total < 2.00 THEN 1 ELSE 0 END) AS 'A',
  -- From 2 up to, but not including, 7. Or [2,7)
  SUM (CASE WHEN 2.00 <= Total and Total < 7.00 THEN 1 ELSE 0 END) AS 'B',
  -- From 7 up to, but not including, 15. Or [7,15)
  SUM (CASE WHEN 7.00 <= Total and Total < 15.00 THEN 1 ELSE 0 END) AS 'C',
  -- From 15 up. [15,]
  SUM (CASE WHEN 15.00 <= Total THEN 1 ELSE 0 END) AS 'D'
FROM
  invoices
© www.soinside.com 2019 - 2024. All rights reserved.