SQL group_by查询

时间:2016-05-31 12:40:43

标签: sql

我有一个表名用户。假设在表格中我有以下字段:

用户ID,UUID1,UUID2

我正在尝试构建以下将返回的SQL查询: .nu​​mber行包括相同的UUID1和UUID2。不是说UUID1等于UUID2,而只是包含两个行(GROUP BY)的行数,另外行数包含UUID1或UUID2(另外,没有分组)。

所以我希望有一个表输出如下: UUID1,UUID2,Number_of_Rows_Contain_both,Number_Of_Rows_Contains_Only_Only_One

知道如何生成这样的查询?

3 个答案:

答案 0 :(得分:2)

希望这是你要求的:

select 
user_id,
sum 
(case when uuid1 is not null and uuid2 is not null then 1 else 0 end) both_uuid_avlbl,
sum
(case when uuid1 is not null then 1 else 0 end) uuid1_avlbl,
sum
(case when uuid2 is not null then 1 else 0 end) uuid2_avlbl
from sample group by user_id;

以下是我用于上述查询的脚本DDL:

   create table sample as  (user_id number(10),uuid1 number(10),uuid2 number(10));
    Insert into sample (USER_ID,UUID1,UUID2) values (1,2,2);
Insert into sample (USER_ID,UUID1,UUID2) values (2,3,2);
Insert into sample (USER_ID,UUID1,UUID2) values (3,1,1);
Insert into sample (USER_ID,UUID1,UUID2) values (4,1,2);
Insert into sample (USER_ID,UUID1,UUID2) values (5,2,0);
Insert into sample (USER_ID,UUID1,UUID2) values (8,null,2);
Insert into sample (USER_ID,UUID1,UUID2) values (7,null,null);
Insert into sample (USER_ID,UUID1,UUID2) values (6,null,2);
Insert into sample (USER_ID,UUID1,UUID2) values (3,null,1);
Insert into sample (USER_ID,UUID1,UUID2) values (1,3,2);
Insert into sample (USER_ID,UUID1,UUID2) values (1,null,2);
Insert into sample (USER_ID,UUID1,UUID2) values (5,3,0);
Insert into sample (USER_ID,UUID1,UUID2) values (5,3,null);
insert into sample (user_id,uuid1,uuid2) values (5,null,null);

我使用的是Oracle 11g。

答案 1 :(得分:1)

对于您的结果,您可以这样做:

    declare @both INT
    declare @a INT
    declare @b INT
    declare @c INT
    select @both = count(*) from users where UUID1  is not null and UUID2 is not null 
    select @a = count(*) from users where UUID1  is not null and UUID2 is  null 
    select @b = count(*) from users where UUID1  is  null and UUID2 is not null 
    select @c = count(*) from users where UUID1  is  null and UUID2 is  null 
    Select @both as BothCount,@a AS UUID1Count,@b AS UUID2Count,@c AS Bothnull

答案 2 :(得分:0)

让我首先理解你的问题; 表格格式如下;

user_id,UUID1, UUID2
1 a a 
2 a b
3 b b
4 b c
5 d c

并且您要查找的此类输入样本的输出如下所示;

a   1   1
b   1   2
c   0   2
d   0   1

可能的解决方案是;

SELECT UUID, sum(SAME) SAME, sum(DIFFERENT - SAME) DIFFERENT
FROM (
    select a.UUID, 
      case when (a.UUID = t.UUID1 and a.UUID = t.UUID2) THEN 1 else 0 end SAME,
      case when a.UUID = t.UUID1 or a.UUID = t.UUID2 THEN 1 else 0 end DIFFERENT
    from 
    (
        select distinct UUID1 as UUID
        from  THE_TABLE

        UNION

        select distinct UUID2 as UUID
        from  THE_TABLE
    ) a,  THE_TABLE t
) GROUP BY UUID

使用DB2 v 10.5.5进行测试