T1 : 省市名称数据表
____________________________
省份        
____________________________
河南        
河北        
湖南        
湖北        
上海
北京
山东        
_______________________________
T2 ,记录省市人数
____________________________
省份        人数
____________________________
河南        45
河北        56
湖南        35
湖北        45
上海        98
_______________________________我要查询出一条记录结果为:河南    河北     湖南       湖北        上海        北京       山东
————————————————————————————————————
45      56         35        45         98           0         0————————————————————————————————————请教怎么写?  谢谢在线结贴! 学习。

解决方案 »

  1.   

    select T1.省份,case when T2.记录省市人数 is null then 0 else T2.记录省市人数 end as 人数 from T1 left join T2 where T1.省份=T2.省份
      

  2.   

    create table T1(省份 varchar(10))   
    insert into t1 values('河南')   
    insert into t1 values('河北')   
    insert into t1 values('湖南')   
    insert into t1 values('湖北')   
    insert into t1 values('上海')
    insert into t1 values('北京')
    insert into t1 values('山东')   
    create table T2(省份 varchar(10),人数 int)
    insert into t2 values('河南', 45)
    insert into t2 values('河北', 56)
    insert into t2 values('湖南', 35)
    insert into t2 values('湖北', 45)
    insert into t2 values('上海', 98)
    godeclare @sql varchar(8000)
    set @sql = ''
    select @sql = @sql + ' , max(case t1.省份 when ''' + 省份 + ''' then 人数 else 0 end) [' + 省份 + ']'
    from (select distinct 省份 from t1) as a
    set @sql = 'select ' + substring(@sql , 3, len(@sql)) + ' from t1 , t2 where t1.省份 = t2.省份'
    exec(@sql) drop table t1 , t2/*
    北京          河北          河南          湖北          湖南          山东          上海          
    ----------- ----------- ----------- ----------- ----------- ----------- ----------- 
    0           56          45          45          35          0           98
    */
      

  3.   

    CREATE TABLE #1(省份 varchar(20))
    INSERT #1 SELECT '河北'   
    union all select '湖南'   
    union all select '湖北'   
    union all select '上海'
    union all select '北京'
    union all select '山东'  
    CREATE TABLE #2(省份 varchar(20), 人数 int)
    INSERT #2 SELECT '河南', 45
    union all select '河北', 56
    union all select '湖南', 35
    union all select '湖北', 45
    union all select '上海', 98DECLARE @sql VARCHAR(1000)
    SELECT @SQL=ISNULL(@sql+',','')+'max(case when a.省份='''+省份+''' then 人数 else 0 end) ['+省份+']' from #1
    EXEC('SELECT '+@sql+' FROM #1 a LEFT JOIN #2 b ON a.省份=b.省份')DROP TABLE #1,#2
    --result
    /*河北          湖南          湖北          上海          北京          山东          
    ----------- ----------- ----------- ----------- ----------- ----------- 
    56          35          45          98          0           0*/