递归SQL列子选择

时间:2014-01-17 20:21:19

标签: sql sql-server-2008 recursion subquery

我很抱歉这个问题没有更好的标记,我不知道如何描述没有例子。这就是我想要实现的目标。

我的简化数据:

ID  ParamName ParamValue
-----------------------
1  'Item Code'   '100'
1  'Amount'      '.99'
2  'Item Code'   '555'
2  'Amount'      '1.99'
2  'Item Code'   '200'
2  'Amount'      '2.99'
2  'Item Code'   '221'
2  'Amount'      '.89'

我需要编写一个查询来返回2列中的数据(如果单个ID的多个值,假设项目代码和数量按照它们在表中的顺序匹配):

ItemCode    Amount
-----------------------
'100'      '.99'
'555'      '1.99'
'200'      '2.99'
'221       '.89'

这是我最接近的,但是当有多个具有相同ID的项目代码时,我不想用Max()和Sum()对它们进行分组。我假设需要进行某种递归,但我甚至不知道从哪里开始研究。

select
(Select Max(ParamValue) from EventDetail where id = base.id and ParamName = 'Item Code') as ItemCode,
(Select Sum(ParamValue) from EventDetail where id = base.id and ParamName = 'Amount') as Amount
from 
(
  select distinct id from EventDetail
) base

SQL小提琴:http://sqlfiddle.com/#!2/09b773/1/0

感谢您的观看!

1 个答案:

答案 0 :(得分:0)

让我们首先看一下简单的情况,即有一些方法可以将项目代码和项目数量组合在一起。

所以数据看起来像这样:

ID  ParamName ParamValue
-----------------------
1  'Item Code'   '100'
1  'Amount'      '.99'
2  'Item Code'   '555'
2  'Amount'      '1.99'
3  'Item Code'   '200'
3  'Amount'      '2.99'
4  'Item Code'   '221'
4  'Amount'      '.89'


WITH uniqueRowID AS
(
   SELECT DISTINCT ID
   FROM myTable
)
SELECT uniqueRowID, Item.ParamValue as Item, Amount.ParamValue as Amount
FROM uniqueRowID
JOIN myTable as Item ON uniqueRowID.ID = Item.ID AND Item.ParamName='Item Code'
JOIN myTable as Amount ON uniqueRowID.ID = Amount.ID AND Amount.ParamName='Amount'

现在,在您的情况下,您需要有一些方法来订购项目 - 您可能需要将其添加到您的表中 - 我将调用此列myOrder

要获得上述分组,我们会执行以下操作:

WITH item AS
(
   SELECT ParamValue,
          ROW_NUMBER() OVER (ORDER BY myOrder) as rn
   FROM myTable 
   WHERE ParamName = 'Item Code'
), amount AS
(
   SELECT ParamValue,
          ROW_NUMBER() OVER (ORDER BY myOrder) as rn
   FROM myTable 
   WHERE ParamName = 'Amount'
)
SELECT item.ParamValue as ItemCode, amount.ParamValue as Amount
FROM item
JOIN amount ON item.rn = amount.rn