如何从其他表中获取数据到一个表并显示它?

时间:2014-06-06 18:11:05

标签: select sum case average

table1
no   | date    | 
J001 | 06 June |

table2
no   | code | qty |  /// AVGprice | Total
J001 | B001 |  5  |  /// 1500     | 7500
J001 | B003 |  7  |  /// 1000     | 7000

table3                                   table4
code | name        | AVGPrice            no   | code | Price
B001 | procc       | 1500                M001 | B001 | 1000
B002 | motherboard | 2000                M001 | B002 | 2000
B003 | VGA card    | 1000                M002 | B001 | 2000
                                         M002 | B003 | 1000

我从此查询获得AVGprice

select t.code, t.name, t.avg
from (select table3.code, table3.name, (
         select avg(table4.price)
         from table4
         where table4.code=table3.code)as 'avg'
      from table3
)as t

我能做的结果是

no  | date    | Info   
J001| 06 June | ABCDEFG

使用这些查询

select t.no, t.date, t.info
from (select table1.no, table1.date, 'ABCDEFG' as info
      from table1
     )as t

我想要的结果是

no  | date    | Info     | Total
J001| 06 June | ABCDEFG  | 14500  --> from sum of Total

我不知道在哪里提出我的平均查询以及如何总结...

1 个答案:

答案 0 :(得分:0)

以下内容应该添加你需要的子查询来提取平均值,并添加了另一列 给你平均值的总和。

select t.no, 
t.date, 
t.info, 
(select avg(table4.price)
         from table4
         where table4.code=table3.code)as 'avg',
sum(avg)
from (select table1.no, table1.date, 'ABCDEFG' as info
      from table1
     )as t
 group by t.no, t.date, t.info