maybe: use decode and sum

解决方案 »

  1.   

    先通过表一构造一个动态sql查询语句@sql,然后运行execute @sql。
    构造方法视你的具体情况而定。
    比如:
    declare @str varchar(8000),@sql varchar(8000)
    set @str = ''
    select @str = @str + ',' + name from table1
    @sql = 'select 人数,其他查询项' + @str + ' from table2'
    execute @sql
      

  2.   

    or, case and sum in SQL Server
    select sum(case name when '早晨' then 1 else 0 end) as morning,
    sum(case name when '中午' then 1 else 0 end) as noon,
    sum(case name when '晚上' then 1 else 0 end) as evening
    from t
    case name when 'a' then 1 else 0 end
    has counterpart in Oracle as
    decode(name, 'a', 1, 0)