2016-05-31 33 views
-4

我有一個表名用戶。假設在我有以下字段的表:SQL group_by查詢

用戶ID,UUID1,UUID2

我想建立下面的SQL查詢將返回: 。數行既包括同一UUID1和UUID2的。不是UUID1等於UUID2,而是包含兩者(GROUP BY)的行數,另外行數包含UUID1或UUID2(單獨,無分組)。

所以我想有一臺輸出如下: UUID1,UUID2,Number_of_Rows_Contain_both,Number_Of_Rows_Contains_Only_Only_One

任何想法,我怎麼能產生這樣的查詢?

+0

添加一些樣本表數據,和預期的結果。 – jarlh

+0

樣本數據請參閱 – theDbGuy

+0

另請參見:您正在使用哪些DBMS? –

回答

2

希望這是你在aksing什麼:

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。

+0

可能會將此方法稱爲「條件聚合」儘管我不知道是否需要user_ID和group by,因爲OP僅詢問行數,並且「單獨,無分組」 – xQbert

+0

如果不需要,則取出分組。讓事情變得容易理解 – theDbGuy

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 
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