SQL子查询语法帮助

时间:2018-09-07 05:44:23

标签: sql sql-server

我想从一个数据库的单独列中的查询中获取特定值。

如果我运行以下查询:

select  ticker 
        ,calendardate 
        ,marketcap
        ,dimension
from [Investment Data 1].dbo.sf1a
where 
        ticker = 'aapl' 
    and dimension in ('ary','mry')
    and calendardate >='2013-01-01'
order by dimension, calendardate;

我得到以下结果:

ticker  calendardate    marketcap   dimension
AAPL    2013-12-31  472272497794    ARY
AAPL    2014-12-31  616453338265    ARY
AAPL    2015-12-31  664969711644    ARY
AAPL    2013-12-31  438576934018    MRY
AAPL    2014-12-31  603277600250    MRY
AAPL    2015-12-31  654159234917    MRY

我想要一个查询,该查询将返回以下结果:

ticker  calendardate    "ARY Marketcap" "MRY Marketcap"
AAPL    2013-12-31      472272497794    438576934018    
AAPL    2014-12-31      616453338265    603277600250    
AAPL    2015-12-31      664969711644    654159234917    

我该怎么做?

感谢您的宝贵时间。明智的。

1 个答案:

答案 0 :(得分:1)

使用case expression可让您执行conditional aggregates,这具有pivot从行到列的作用

select  ticker 
        ,calendardate 
        ,max(case when dimension = 'ary' then marketcap end) as aryMarketcap
        ,max(case when dimension = 'mry' then marketcap end) as mryMarketcap
from [Investment Data 1].dbo.sf1a
where 
        ticker = 'aapl' 
    and dimension in ('ary','mry')
    and calendardate >='2013-01-01'
group by  ticker 
        ,calendardate 
order by dimension, calendardate;

替代方法是使用pivot运算符

select
      ticker, calendardate, [ary], [mry]
from (select 
            * 
       from table1) p
pivot (
    max(marketcap)
    for dimension IN ([ary],[mry])
    ) pvt

如果您有很多维度想要转到列标题,则可能需要使用dynamic sql来获得最终结果。