SQL将不同的列值选择为一行

时间:2017-02-10 11:50:21

标签: sql

我有一个表格,其值如下:

<telerik:RadMenu Grid.Column="0" 
        Name="MainMenu" 
        Orientation="Vertical" 
        Margin="10,30,0,20"
        Height="1200"
        ItemsSource="{StaticResource MainMenuItemsSource}">
    <telerik:RadMenu.ItemContainerStyle>
        <Style TargetType="telerik:RadMenuItem" BasedOn="{StaticResource {x:Type telerik:RadMenuItem}}">
            <Setter Property="Command" Value="{Binding Command}" />
        </Style>
    </telerik:RadMenu.ItemContainerStyle>
</telerik:RadMenu>

第一行是特定项目的期初余额10。第二行是同一项目的期末余额20。第3行正在打开另一个项目,然后是收盘余额等。我想查询结果显示如下:

StoreID | ItemID | OpeningClosingBalance | Total
1       | 1      | O                     | 10
1       | 1      | C                     | 20
1       | 2      | O                     | 5
1       | 2      | C                     | 7

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:3)

您可以使用条件聚合执行此操作:

select StoreId, ItemId,
       max(case when OpeningClosingBalance = 'O' then total end) as openingbalance,
       max(case when OpeningClosingBalance = 'C' then total end) as closingbalance
from t
group by StoreId, ItemId;