SQL在同一行上创建相同值的列

时间:2018-01-30 20:50:09

标签: sql oracle

我有一个查询,我在同一列上使用不同的loc获得相同的sku,我想在相同的行上添加一个具有相同值的列。

select 
    sku, loc, qty 
from 
    skuxloc 
where 
    loc <> 'STAGE' 
    and sku in (select sku 
                from skuxloc 
                where loc <> 'STAGE' and qty > 0
                group by sku
                having count(distinct loc) > 1)
order by 
    sku, loc

输出:

SKU              LOC    QTY
------------------------------
11704-01150N    08B17   1
11704-01150N    09B21   1
11704-01161N    04A16   1
11704-01161N    05B26   2
11704-01173N    09A22   2

我希望它看起来像这样:

SKU             LOC    QTY   Loc   QTY
---------------------------------------
11704-01150N    08B17   1    09B21  1
11704-01161N    04A16   1    05B26  2
11704-01173N    09A22   2

2 个答案:

答案 0 :(得分:1)

用于SQL-SERVER

http://rextester.com/live/EUYY95359

的演示
declare @myproducts table (SKU varchar(100),LOC varchar(20), qty integer)

insert into @myproducts
values 
('11704-01150N','08B17',   1),
('11704-01150N','09B21',   1),
('11704-01161N','04A16',   1),
('11704-01161N','05B26',   2),
('11704-01173N','09A22',   2)



select 
x.SKU,x.LOC,x.QTY,
y.LOC,y.QTY
from 
(
select 
SKU,LOC,QTY,
row_number() over (partition by SKU order by LOC) pos
from
@myproducts
) x
left outer join
(
select 
SKU,LOC,QTY,
row_number() over (partition by SKU order by LOC) pos
from
@myproducts
) y on y.SKU = x.SKU and y.pos = 2
where x.pos = 1

答案 1 :(得分:0)

这是甲骨文的一个。 你没有指定,但我假设如果sku有多个重复的loc,你想要显示它们。例如。如果sku&#11; 11704-01150N&#39;有3个loc条目,输出应该是什么样的?它应该只显示其中一个副本,还是两者都显示?

select 
    s1.sku, s1.loc, s1.qty, s2.loc, s2.qty 
from 
    skuxloc s1
left join skuxloc s2
    on s2.loc <> 'STAGE'
    and s2.qty > 0
    and s2.sku = s1.sku
    and s2.loc > s1.loc
where 
    s1.loc <> 'STAGE'
    and (s2.loc is not null 
            or (select count(1) from skuxloc s3 
                where s3.sku = s1.sku and s3.qty > 0 
                  and s3.loc <> 'STAGE') = 1)
order by 
    s1.sku, s1.loc;