-2

任何人都可以帮助我使用 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
4

2 回答 2

2

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

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

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

SQL 服务器

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

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

编辑,您说您使用的是 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

如果您不在 Oracle 11g 上,则需要使用CASEwith 聚合函数:

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

于 2012-10-31T14:33:56.940 回答
0

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

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

于 2012-10-31T14:48:38.447 回答