合并具有不同条件的表中的相同列

时间:2017-03-29 18:54:58

标签: sql sql-server

我想从一个表中检索数据,但数据基于这是我的查询条件:

Select 
    Store_ID,
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory 
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim' 
       and Imported_Date = '3-15-2017' 
       and Store_ID like 'S%'),
    (select Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand
     from DailyStockHistory 
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim' 
       and Imported_Date = '3-22-2017' 
       and Store_ID like 'S%')
from 
    DailyStockHistory

请帮助。

提前致谢。

3 个答案:

答案 0 :(得分:1)

为什么不在一个查询中组合条件而不是组合2个查询结果:

Select Store_ID,
     (select Stc_Item_Desc, Imported_Date,Store_ID, Quantity_On_Hand
     from DailyStockHistory 
     where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim' AND
         ((Imported_Date = '3-15-2017') OR (Imported_Date = '3-22-2017'))
         AND Store_ID like 'S%'
      )
     from DailyStockHistory

要获得某一天的Quantity_On_Hand,您只需再进行一次查询

     select Quantity_On_Hand
     from *above result*
     where Imported_Date = '3-15-2017'

答案 1 :(得分:1)

您需要生成PIVOT表格以获得预期的输出,请检查此内容。

示例数据:

Insert Into DailyStockHistory Values('SCCC387','SAWA/QuickNet prepaid triosim','2017-03-15',518)
Insert Into DailyStockHistory Values('SCCC387','SAWA/QuickNet prepaid triosim','2017-03-22',251)

SQL:

Select 
    *
From 
(
    Select 
        Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand 
    From DailyStockHistory
    Where Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim' 
        And Store_ID Like 'S%' 
        And (Imported_Date = '3-15-2017' Or Imported_Date = '3-22-2017')
) AS Data
PIVOT
(
    SUM(Quantity_On_Hand)
    FOR Imported_Date IN ([3-15-2017],[3-22-2017])
) AS PIVOTData

输出:

enter image description here

3-15-2017&根据{{​​1}}日期,3-22-2017Quantity_On_Hand数量的列。

答案 2 :(得分:0)

Select 
    Stc_Item_Desc, Imported_Date, Store_ID, Quantity_On_Hand 
From 
    DailyStockHistory 
Where
    Stc_Item_Desc = 'SAWA/QuickNet prepaid triosim' 
    And Store_ID Like 'S%' 
    And (Imported_Date = '3-15-2017' Or Imported_Date = '3-22-2017)