简体   繁体   中英

Total sum of multiple columns in Oracle SQL Statement by unique ID

I have a table of members_id and Flags . I want to sum up how many flags a member_id has (like below). I have about 19 Flags which can have a 1 or 0 in the flag field . So basically I want to sum up the 1 in each column per Member_Id

Member_Id | Flag2| Flag3| Flag4|Flag5|Flag6|Flag7|Flag8|
999999b     1        0      0    0     1       1      1    
777777a     0        1      1    0     1       0      0

Desired Result

Member_Id |  Total
999999b        4
777777a        3

You could use:

SELECT Member_id, Flag1+Flag2+...+ Flag19 AS total
FROM tab;

If any column is nullable you have to handle it for example by using COALESCE :

SELECT Member_id, COALESCE(Flag1,0) + COALESCE(Flag2,0) + ...
FROM tab;
Select Member_id, sum(Flag1_Flag2_flag3+....Flag19) as Total_Flags from table group by Member_id;

You might try using UNPIVOT :

SELECT member_id, SUM(COALESCE(flag_value, 0)) AS total_value FROM (
    SELECT member_id, flag_name, flag_value
      FROM (
        SELECT member_id, flag2, flag3, flag4, flag5, flag6, flag7, flag8 -- etc.
          FROM yourtable
    ) UNPIVOT (
        flag_value FOR flag_name IN
          ( flag2, flag3, flag4, flag5, flag6, flag7, flag8 )
    )
) GROUP BY member_id;

The subquery above is also how you could normalize your data, either in a view, materialized view, or new table:

CREATE VIEW yourview AS
SELECT member_id, flag_name, flag_value
  FROM (
    SELECT member_id, flag2, flag3, flag4, flag5, flag6, flag7, flag8 -- etc.
      FROM yourtable
) UNPIVOT (
    flag_value FOR flag_name IN
      ( flag2, flag3, flag4, flag5, flag6, flag7, flag8 )
);

Then querying it and summing the values of the flags becomes much easier.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM