两个基于字段值的计数

时间:2016-12-06 14:15:00

标签: sql firebird firebird-3.0

我有一个表table1field1的值为1到5我需要获取field1 = 1时的记录数和{{1时的剩余记录数}}。所以我可以这样做:

field1 <> 1

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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

如果您不想创建中间表,您还可以使用子查询解决方案。这个应该做你正在寻找的:

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)

希望这有帮助。

答案 2 :(得分:1)

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

提示: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