日期:2014-05-18  浏览次数:20658 次

SQL数据库查询问题!!
HTML code
 表1:
    <table>
     <tr>
      <td>Name</td>
      <td>数量</td>
     </tr>
     <tr>
      <td>A</td>
      <td>100</td>
     </tr>
     <tr>
      <td>B</td>
      <td>200</td>
     </tr>
     <tr>
      <td>A</td>
      <td>150</td>
     </tr>
     <tr>
      <td>A</td>
      <td>100</td>
     </tr>
     <tr>
      <td>B</td>
      <td>300</td>
     </tr>
    </table>
    <br />
    表2:
    <table>
     <tr>
      <td>Name</td>
      <td>单价</td>
     </tr>
     <tr>
      <td>A</td>
      <td>0.2</td>
     </tr>
     <tr>
      <td>B</td>
      <td>0.6</td>
     </tr>
    </table>
    <br />
    查询结果:
    <table>
     <tr>
      <td>Name</td>
      <td>数量</td>
      <td>总价</td>
     </tr>
     <tr>
      <td>A</td>
      <td>3</td>
      <td>70</td>
     </tr>
     <tr>
      <td>B</td>
      <td>2</td>
      <td>300</td>
     </tr>
    </table>

如上,要怎么写?

------解决方案--------------------
SQL code

select 
    a.name,
    sum(a.数量)*b.单价 as 合计 
from 
    tb1 a
inner join
    tb2 b
on 
    a.name=b.name
group by 
    a.name

------解决方案--------------------
SQL code
create table #A
(
    name nvarchar(10),
    number int
)

insert into #A
select 'A', 100

insert into #A
select 'B', 200
union
select 'A', 150
union
select 'A', 100
union
select 'B', 300

create table #B
(
    name nvarchar(10),
    price decimal(5, 1)
)

insert into #B
select 'A', 0.2
union
select 'B', 0.6

--Query--
select a.name, count(*) as number, sum(a.number * b.price) as totPrice
from #A a, #B b
where a.name = b.name
group by a.name
order by a.name

--name    number    totPrice
--A    3    70.0
--B    2    300.0