sql pivot并组合两个查询

时间:2016-05-31 16:02:35

标签: sql-server sql-server-2008 stored-procedures pivot

我在存储过程中有以下查询,它提取所提供产品代码的商店信息和数量:

select l.region, l.region_description, s.store_code as store, s.name, s.city, p.province_code, s.telephone,  b.store_code, b.prod_code,  b.prod_id,  
sum(convert(int, b.bin_qty_stocks)) as inv
,  dbo.bb_fnGHBQt(c.Channel_Index - 1, b.prod_id) as web_hb
,  case when b.store_code = '0030' then sum(convert(int, bin_qty_stocks))  - dbo.bb_fnGHBQt(c.Channel_Index - 1, prod_id) 
    else sum(convert(int, b.bin_qty_stocks))  end as inv_avail
from store s (nolock)
    inner join province p
        on p.province_id = s.province_id
    inner join bb_vStoreLevels l (nolock) 
        on l.store_code_id = s.store_Code_id
    left join bb_bin b (nolock)
        on b.store_code_id = s.store_code_id
        and b.B_Code in ('ST', 'BC', 'R') 
        and b.prod_code = @inSKU
    cross join bb_B2B_Channel c (nolock)            
where (((l.region is not null) and (l.region <> '077')) or (l.store = '0030'))
    and s.store_code <> '0055'
    and (l.date_opened <= getdate())
    and ((l.date_closed is null) or (l.date_closed > getdate()))    
    and c.channel_description = 'WWW'   
GROUP BY l.region, l.region_description, s.store_code, s.name, s.city, p.province_code, s.telephone
, b.store_code, b.prod_code, b.prod_id, c.Channel_Index

然后我有另一个存储过程,水平列出给定SKU的最多6个兄弟:

;WITH X AS 
   (
    SELECT prod_code, Parent_Sku, Parent_Child_Priority, ROW_NUMBER() OVER (PARTITION BY Parent_Sku ORDER BY Parent_Child_Priority DESC) rn 
    FROM bb_Product 
    WHERE
        Parent_SKU in (SELECT Parent_SKU
                        FROM bb_Product
                        WHERE prod_code = @inSKU)
        and ParentFlag <> 'P'
        and prod_code <> @inSKU
    ),
Y AS (
      SELECT * , 'Sib' + ISNULL(NULLIF(Cast(rn AS Varchar(10)), '0'),'') Sibs
      FROM X
      WHERE rn < 7 
)
 SELECT Sib1,Sib2,Sib3,Sib4,Sib5,Sib6
 FROM 
    (
    SELECT Parent_Sku , Sibs , prod_code
    FROM Y
    ) a
     PIVOT (MAX(prod_code)
            FOR Sibs
            IN (Sib,Sib1,Sib2,Sib3,Sib4,Sib5,Sib6))p

我想要做的是将这两个查询合并到一个存储过程中,这样我就可以列出兄弟(inv)数量和原始项目数量。它看起来如下所示:

region  region_description  store   name    city    province_code   telephone   store_code  product_code    product_id  inv web_hb  inv_avail   sib1    sib2    sib3    sib4    sib5    sib6

001         001-CO          0042    XYZ Colorado Springs    CO        123-123-1234  0042    1234566         123456784   1   0           1       1       0       1       4       1       2

我之前没有做过这样的事情,所以会欣赏一些输入和方向来实现所需的输出。 谢谢,非常感谢任何帮助。

0 个答案:

没有答案