简体   繁体   中英

Adding column to another table in SQL

I have a table of three numbers that are the percent difference of other numbers.

The query I've used looks like this:

select abs((((select avg(Number) from Table1 where File='File1') - 
    (select avg(Number) from Table1 where File='File2')) / 
    (select avg(Number) from Table1 where File='File2'))*100)
union all
select abs((((select avg(Number) from Table1 where File='File3') - 
    (select avg(Number) from Table1 where File='File4')) / 
    (select avg(Number) from Table1 where File='File4'))*100)
union all
select abs((((select avg(Number) from Table1 where File='File5') - 
    (select avg(Number) from Table1 where File='File6')) / 
    (select avg(Number) from Table1 where File='File6'))*100)

which results in a table like this:

| (No column name) |
|:----------------:|
|             1.54 |
|             1.15 |
|             2.04 |

These numbers are the percent difference for a category of data from three files. These file names are Column1 in Table1 . How could I write this query so that the table looks like this instead? (Add the file names in a column to the left of these numbers).

| FileName | (No column name) |
|:--------:|:----------------:|
| File1    |             1.54 |
| File2    |             1.15 |
| File3    |             2.04 |

Simply add the file name to the query:

select FileName='File1', PCT_DIFF=abs((((select avg(Number) from Table1 where File='File1') - 
    (select avg(Number) from Table1 where File='File2')) / 
    (select avg(Number) from Table1 where File='File2'))*100)
union all
select 'File3', abs((((select avg(Number) from Table1 where File='File3') - 
    (select avg(Number) from Table1 where File='File4')) / 
    (select avg(Number) from Table1 where File='File4'))*100)
union all
select 'File5', abs((((select avg(Number) from Table1 where File='File5') - 
    (select avg(Number) from Table1 where File='File6')) / 
    (select avg(Number) from Table1 where File='File6'))*100)

Simplify the query!

select file,
       100 * (prev_avg - avg) / avg as percent_diff
from (select file, avg(Number) as avg,
             lag(avg(Number)) over (order by file) as prev_avg
      from table1
      where file in ('File1', 'File2', 'File3', 'File4', 'File5', 'File6')
      group by file
     ) t
where file in ('File2', 'File4', 'File6');

This assumes that the files are ordered by name. If should be easy to modify if they are ordered in some other way -- say by date or size.

This also readily generalizes to additional rows.

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