要加入的SQL语句并在多列中给出结果

时间:2012-10-31 14:17:42

标签: sql oracle join pivot

任何人都可以帮助我使用sql语句来生成以下结果吗?

Table Person
Person_ID  Name
1          John
2          Paul

Table Declaration
Decl_ID             Person_ID   Amount
1                   1               10
2                   2               12
3                   1               99
4                   1               24

SQL语句的结果应如下所示:

Name    Amount1 Amount2 Amount3
John    10      99      24
Paul    12

2 个答案:

答案 0 :(得分:2)

您没有指定RDBMS,但如果您的数据库可以访问该功能,那么这基本上是pivot。如果没有,那么您可以使用case和聚合函数进行复制。

<击>的的MySQL

<击>
select name,
  sum(case when group_rn = 1 then amount else 0 end) Amount1,
  sum(case when group_rn = 2 then amount else 0 end) Amount2,
  sum(case when group_rn = 3 then amount else 0 end) Amount3
from
(
  select name,
    @num := if(@name = `name`, @num + 1, 1) as group_rn,
    @name := `name` as dummy,
    amount
  from
  (
    select p.name,
      d.amount,
      d.decl_id
    from person p
    inner join declaration d
      on p.person_id = d.person_id
  ) src
  order by name
) p
group by name

SQL Fiddle with Demo

在SQL Server和Oracle中,存在PIVOT函数:

SQL Server

select name,
  [1] as Amount1,
  [2] as Amount2,
  [3] as Amount3
from
(
  select p.name,
    d.amount,
    row_number() over(partition by p.name order by d.amount) rn
  from person p
  inner join declaration d
    on p.person_id = d.person_id
) src
pivot
(
  sum(amount)
  for rn in ([1], [2], [3])
) p

请参阅SQL Fiddle with Demo

如果您要将未知数量的金额转换为列,则可以创建动态版本。

编辑,你说你使用的是Oracle,所以oracle的具体答案如下:

Oracle 11g具有pivot功能:

select name,
  Amount1,
  Amount2,
  Amount3
from
(
  select p.name,
    d.amount,
    row_number() over(partition by p.name order by d.amount) rn
  from person p
  inner join declaration d
    on p.person_id = d.person_id
) src
pivot
(
  sum(amount)
  for rn in ('1' as Amount1, '2' as Amount2, '3' as Amount3)
) p

请参阅SQL Fiddle with Demo

如果您不使用Oracle 11g,则需要使用具有聚合函数的CASE

select name,
  sum(case when rn = 1 then amount else 0 end) Amount1,
  sum(case when rn = 2 then amount else 0 end) Amount2,
  sum(case when rn = 3 then amount else 0 end) Amount3
from
(
  select p.name,
    d.amount,
    row_number() over(partition by p.name order by d.amount) rn
  from person p
  inner join declaration d
    on p.person_id = d.person_id
) src
group by name

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

我认为你所寻找的是一个动态的支点。 问题是,当您需要动态数据透视时,需要以字符串形式执行查询。

找到示例:http://www.sqlhub.com/2009/05/generic-stored-procedure-for-pivot-in.html