简体   繁体   中英

improving the sql from an existing sql - postgres database

I am not much familiar with the sql. I am using postgres for the database. I got the result from the following sql. I have multiple columns, but I simplified the table and query for this question.

select sum(column1), sum(column2), sum(column3), sum(column4), substring(product, 0, POSITION('-' in product)) as product_code
from table group by product_code order by product_code


column1, column2, column3, column4,   code
10          3       0           2     ABC1
11          4       0           4     ABC2
12          2       0           3     ABC3
13          1       0           6     ABC4

How should I fix the sql from above to get the following result as below?

column1, column2, column3, column4,   code
10          3       0           0     ABC1
10          0       0           2     ABC1
11          4       0           0     ABC2
11          0       0           4     ABC2
12          2       0           0     ABC3
12          0       0           3     ABC3
13          1       0           0     ABC4
13          0       0           6     ABC4

If I use this query with 'union' keyword, I can get the result(as above) that i want, but I am wondering if there is a better way to do it.

select sum(column1), sum(column2), sum(column3), sum(column4), substring(product, 0, POSITION('-' in product)) as product_code
 from table group by product_code union select sum(column1), sum(column2), sum(column3), sum(column4), substring(product, 0, POSITION('-' in product)) as product_code
 from table group by product_code

You want all combinations of code with 10, 11, 12, and 13 in the first column. Use a cross join to generate the combinations and then a left join to bring in the existing data:

select gs.c1, coalesce(t.c2, 0), coalesce(t.c3, 0), coalesce(t.c4, 0, 
       c.product_code
from (select distinct substring(product, 1, POSITION('-' in product)) as product_code from t) c cross join
     generate_series(10, 13, 1) as gs(c1) left join
     (select sum(column1) as c1, sum(column2) as c2,
             sum(column3) as c3, sum(column4) as c4,
             substring(product, 1, POSITION('-' in product)) as product_code
      from t
      group by code
     ) t
     on t.product_code = c.product_code and t.c1 = gs.c1
order by c.product_code

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