基于字段值的两个计数

two counts based on field value

我有一个 table table1 有一个 field1 的值从 1 到 5 我需要在 field1 = 1field1 <> 1时的剩余记录。所以我可以这样做:

select count(*) from table1
group by field1 = 1

然而,这会给我两个正确的值作为结果中的两条记录,但我想知道有没有办法将两个计数值作为一个 select SQL 中的列?

create table onetwofive (field1 int)
go
insert into onetwofive (field1) values
    (1),(2),(3),(4),(5),(1),(1),(2)
go
select (select count(*) from onetwofive where field1 = 1) ones,
       (select count(*) from onetwofive where field1 <> 1) others
       from rdb$database

如果你不想创建中间table,你也有子查询解决方案。这个应该可以满足您的需求:

select distinct * from
(select count(*) as ones from table1 group by field1 having field1 = 1) as ones 
join 
(select count(*) as not_ones from table1 group by field1 having field1 <> 1) as not_ones;

你应该得到类似下面的内容:

+------+----------+
| ones | not_ones |
+------+----------+
|  9   |      6   |
+------+----------+
1 row in set (0,00 sec)

希望对您有所帮助。

实际上您不需要子选择。使用一个查询就够了。

提示:SQL-标准聚合函数忽略所有 NULL 值。

c:\Program Files\Firebird\Firebird_3_0>isql
Use CONNECT or CREATE DATABASE to specify a database
SQL> create database "b:\testfb3.fdb" ;

SQL> create table oneTwoFive (field1 int);

SQL> set bulk_insert insert into onetwofive(field1) values (?);
BULK> (1)
BULK> (2)
BULK> (3)
BULK> (4)
BULK> (5)
BULK> (1)
BULK> (1)
BULK> (2)
BULK>

SQL> select * from onetwofive;

      FIELD1
============
           1
           2
           3
           4
           5
           1
           1
           2

SQL> select distinct count(*), field1=1 as "Is One Flag" from onetwofive
CON> group by 2;

                COUNT Is One Flag
===================== ===========
                    3 <true>
                    5 <false>

SQL> select
CON> count(case when field1=1 then 1 else null end) "When One",
CON> count(case when field1=1 then null else 1 end) "Rest"
CON> from oneTwoFive;

             When One                  Rest
===================== =====================
                    3                     5