需要有关将相邻行组合成单行的SQL查询的帮助

时间:2009-07-15 16:45:13

标签: sql sql-server tsql

我需要一个具有下面列出的表结构的问题的解决方案。 输入

1 1/1/2009产品1
2 2/2/2009产品2
3 3/3/2009产品3
4 4/4/2009产品4
5 5/5/2009产品5

输出

1 1/1/2009 2/2009产品1
2 3/3/2009 4/4/2009产品3
3 5/5/2009 Product5

我尝试过使用CTE。但是在提取第二行值时并不是非常成功。 感谢任何帮助。感谢。

3 个答案:

答案 0 :(得分:1)

您正在寻找PIVOT:http://msdn.microsoft.com/en-us/library/ms177410.aspx
这是你给出的信息的最佳镜头,我在我的一个应用程序中做了类似的事情。如果透视值更改,则可能需要使用动态SQL查询。

SELECT *
    FROM (SELECT [Date]
        ,[Product] 
      FROM [Values]
   PIVOT (Max([Date])
          FOR [Product]
           IN ('put date ranges here')) pvt

这是我的样子,这将允许一组不同的值。这在表单构建器中用于检索用户输入的值

--//Get a comma delimited list of field names from the field table for this form
DECLARE @FieldNames varchar(max)
SELECT @FieldNames = COALESCE(@FieldNames + ', ', '') + '[' + CAST([FieldName] AS varchar(max)) + ']'
  FROM [Fields]
 WHERE [FormID] = @FormID

--//create a dynamic sql pivot table that will bring our 
--//fields and values together to look like a real sql table
DECLARE @SQL varchar(max)
SET @SQL = 
 'SELECT *
    FROM (SELECT [Values].[RowID]
            ,[Fields].[FieldName]
            ,[Values].[Value] 
            FROM [Values]
      INNER JOIN [Fields] ON [Fields].[FieldID] = [Values].[FieldID]
           WHERE [Fields].[FormID] = ''' + @FormID + ''') p
   PIVOT (Max([Value])
      FOR [FieldName]
      IN (' + @FieldNames + ')) pvt'

--//execute our sql to return the data
EXEC(@SQL)

答案 1 :(得分:1)

我不知道Russ的回答是否对你有帮助。 Here is a link一篇文章解释了如何在查询结果中添加行号。 (搜索“row_number”以找到最可能的示例。)

一旦你有一个正确对行进行编号的查询,你应该能够将它扔进CTE,然后从中选择两次 - 一次是奇数,再一次是偶数。每个结果都返回偶数编号的值(奇数 - 1 =偶数)。此时,您可以加入查询结果并在一行中获得两个产品。

答案 2 :(得分:0)

您实际上可以最初创建一个虚拟列并创建一个cte。

然后,使用cte并将它们连接到虚拟键和行号或模拟顺序号的序列上。

然后,在数据集中过滤以仅显示奇数行

create table dbo.test
(
    id integer,
    currdate varchar(20), -- just to keep simple, not to mess with dates, took this as string
    productCode varchar(20)
);


insert into test values (1, '1/1/2009', 'product1');
insert into test values (2, '2/2/2009', 'product2');
insert into test values (3, '3/3/2009', 'product3');
insert into test values (4, '4/4/2009', 'product4');
insert into test values (5, '5/5/2009', 'product5');


with ctes as
(
    select
        't' as joinKey,
        id, -- serves as rownum or else create another using row_num() over partition by and order by
        currdate,
        productCode     
    from test
)
select
    c1.id,
    c1.currdate,
    c1.productCode,
    c2.id,
    c2.currdate,
    c2.productCode
from
(
    select
        joinKey,
        id,
        currdate,
        productCode
    from
        ctes
)c1,
(
    select
        joinKey,
        id,
        currdate,
        productCode
    from
        ctes
)c2
where c1.joinKey = c2.joinKey
and c1.id + 1 = c2.id
and c1.id % 2 = 1

结果如下图所示:

id  currdate    productCode id  currdate    productCode
1   1/1/2009    product1    2   2/2/2009    product2
3   3/3/2009    product3    4   4/4/2009    product4
相关问题