在SQL中将列添加到另一个表

时间:2017-05-12 19:08:06

标签: sql sql-server

我有一个三个数字表,这是其他数字的百分比差异。

我使用的查询如下所示:

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)

会产生如下表:

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

这些数字是三个文件中一类数据的百分比差异。这些文件名在Column1中为Table1。我怎么能写这个查询,以便表格看起来像这样? (在这些数字左侧的列中添加文件名)。

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

2 个答案:

答案 0 :(得分:5)

只需将文件名添加到查询中:

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)

答案 1 :(得分:2)

简化查询!

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');

这假设文件按名称排序。如果以其他方式订购,比如按日期或尺寸订购,应该很容易修改。

这也很容易推广到其他行。