另一个SQL'Rows to Columns'问题

时间:2011-06-23 22:24:34

标签: sql sql-server

这是我的数据:

ID 模型
1 思域 2008年
1 符合 2010
2 野马 2011
3 塔霍 2011   

我想得到这个结果:

ID 型号1 YEAR1 模型2 YEAR2
1 思域 2008年 符合 2010
2 野马 2011
3 塔霍 2011   

每个ID下最多可以有4辆车,不能再出现。我花了很多时间研究这个,但没有找到一个完全适合我的例子的好解决方案。也许是因为我不知道如何准确地说出我的搜索。感谢...

2 个答案:

答案 0 :(得分:1)

您应该使用PIVOT表。这很难看,但它确实有效:

if object_id('tempdb..#RepeatingGroup') is not null drop table #RepeatingGroup
select 1 as ID, 'Civic' as Model, '2008' as [Year] into #RepeatingGroup union all
select 1, 'Accord', '2010' union all
select 2, 'Mustang', '2011' union all
select 3, 'Tahoe', '2011'

if object_id('tempdb..#tmp') is not null drop table #tmp
select
    ID,
    Model,
    Year,
    row_number() over (partition by x.ID order by x.Model) as Ordinal
into
    #tmp
from
    #RepeatingGroup x

select
    pvtMd.ID,
    pvtMd.[1] as Model1,
    pvtYr.[1] as Year1,
    pvtMd.[2] as Model2,
    pvtYr.[2] as Year2,
    pvtMd.[3] as Model3,
    pvtYr.[3] as Year3,
    pvtMd.[4] as Model4,
    pvtYr.[4] as Year4
from
    (select ID, Model, Ordinal from #tmp t) t
    pivot (
        min(Model) for Ordinal in ([1], [2], [3], [4])
    ) as pvtMd,
    (select ID, Year, Ordinal from #tmp t) t2
    pivot (
        min([Year]) for Ordinal in ([1], [2], [3], [4])
    ) as pvtYr
where
    pvtMd.ID = pvtYr.ID
order by
    1

答案 1 :(得分:0)

在SQL中没有一种非常好的方法可以做到这一点。您可能会尝试使用数据透视表,但每个实体都需要一个序列。

你最好的选择是按照你的输出语言安排你想要的东西,这将有更好的工具可用于此类事情。

为名为sequence(包含1,2,3和4)

的每一行添加一列
SELECT
id,
Max(case when seq = 1 then model end) as model1,
max(case when seq = 1 then year end) as year1,
Max(case when seq = 2 then model end) as model2,
max(case when seq = 2 then year end) as year2,
Max(case when seq = 3 then model end) as model3,
max(case when seq = 3 then year end) as year3,
Max(case when seq = 4 then model end) as model4,
max(case when seq = 4 then year end) as year4
group by id