Search code examples
sqlpostgresqlpostgresql-12

Search and match indexes in two different columns, return the sum of a third column - Postgresql


I have a table called "tax_info", this table stores the information of the land tax of my city, it goes like this:

taxpayer_code  |  condominium_num  |  lot_area  |  built_area
-------------------------------------------------------------
0010030078-2   |     00-0          |   143      |    130
0010030079-1   |     02-7          |   283      |    57
0010030080-1   |     02-7          |   283      |    48
0010030081-1   |     02-7          |   283      |    50

the taxpayer code first 3 numbers refer to the city district, the next 3 to the block within the district, and the next 4 can refer to the lot in a block if the condo number is 00-0, or to an apartment, or store, etc if the condo number is different than 00-0, in which case all equal condo numbers refer to the same lot within the block.

what I want to do is pass a list of "taxpayer_code" and get the "lot_area" and "built_area" for the lots. the problem is, if the person lives in a condo, her apartment is a fraction of the total built area for the lot. So, if I search for code 0010030078% (the -X number doesn't matter) the result is: Lot Area = 143 and Built Area = 130

But if I search for 0010030080%, the result I expect is: Lot Area = 283 and Built Area 155

And if I search for 0010030078%, 0010030079%, the result: Lot Area = 426 and Built Area 285

So the database should get the taxpayer codes, then look if the condominium number is different from 00-0 for each code passed, if so, it should add to the sum all the other taxpayer codes that share the same condo number within the same district and block. (ideally, if tax codes belonging to different districts or blocks are passed a warning should be returned, and if more tax codes are added to the sum, a listing with all codes added would be nice, but it's okay if that's too much of a hassle!).

I am new to SQL and can't wrap my head around this, I appreciate every help you can give me, thanks!


Solution

  • Hmmm . . . use a subquery and window functions to add up the values that you want:

    select ti.*
    from (select ti.*,
                 (case when condominium_num <> '00-0'
                       then sum(built_area) over (partition by condominium_num)
                       else built_area
                  end) as real_built_area
          from tax_info ti
         ) ti
    where . . .