日期   支付方式  金额
1       点卡     10
1       直冲     20
2       点卡     30
2       直冲     40sql怎么实现如下:
日期   点卡    直冲  
1       10     20
2       30     40

解决方案 »

  1.   

    select 日期,
    sum(case when 支付方式='点卡' then 金额 else 0 end) as 点卡,
    sum(case when 支付方式='直冲' then 金额 else 0 end) as 直冲
    from tb
    group by 日期
      

  2.   

    ---测试数据---
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([日期] int,[支付方式] varchar(4),[金额] int)
    insert [tb]
    select 1,'点卡',10 union all
    select 1,'直冲',20 union all
    select 2,'点卡',30 union all
    select 2,'直冲',40
     
    ---查询---
    select 日期,
    sum(case when 支付方式='点卡' then 金额 else 0 end) as 点卡,
    sum(case when 支付方式='直冲' then 金额 else 0 end) as 直冲
    from tb
    group by 日期
    ---结果---
    日期          点卡          直冲          
    ----------- ----------- ----------- 
    1           10          20
    2           30          40(所影响的行数为 2 行)
      

  3.   

    creATE TABLE #TT(
    日期 INT,
     支付方式 VARCHAR(5),
       金额 INT)
       
       INSERT #TT
       SELECT 1,'点卡',10 UNION ALL
       SELECT 1,'直冲',20 UNION ALL
       SELECT 2,'点卡',30 UNION ALL
       SELECT 2,'直冲',40 
       
       
       SELECT 日期
    ,SUM(CASE WHEN 支付方式='点卡' THEN 金额 ELSE 0 END)
    ,SUM(CASE WHEN 支付方式='直冲' THEN 金额 ELSE 0 END)
    FROM #TT
    GROUP BY 日期
      

  4.   

    如果支付方式是不确定的,用动态SQL
    ---查询---
    declare @sql varchar(8000)
    select @sql=isnull(@sql+',','')+'sum(case when 支付方式='''+支付方式+''' then 金额 else 0 end) as ['+支付方式+']'
    from (select distinct 支付方式 from tb) t
    exec ('select 日期,'+@sql+' from tb group by 日期')
    ---结果---
    日期          点卡          直冲          
    ----------- ----------- ----------- 
    1           10          20
    2           30          40
      

  5.   

    --生成测试数据
    declare  @test1 table(日期 int,支付方式 nvarchar(2),金额  int) 
    insert into @test1 select 1,'点卡',10 
    insert into @test1 select 1,'直冲',20 
    insert into @test1 select 2,'点卡',30
    insert into @test1 select 2,'直冲',40
    select  日期,sum(case when 支付方式 ='点卡' then 金额 else 0 end ) as 点卡 ,
    sum(case when 支付方式 ='直冲' then 金额 else 0 end )  as 直冲
    from @test1
    group by 日期
      

  6.   

    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([日期] int,[支付方式] varchar(4),[金额] int)
    insert [tb]
    select 1,'点卡',10 union all
    select 1,'直冲',20 union all
    select 2,'点卡',30 union all
    select 2,'直冲',40
    DECLARE @SQL VARCHAR(8000)
    SET @SQL='SELECT 日期'
    SELECT @SQL=@SQL+',SUM(CASE WHEN 支付方式='''+支付方式+''' THEN 金额 ELSE 0 END)AS '''+支付方式+''''
    FROM (SELECT DISTINCT 支付方式 FROM TB)AS T
    --SELECT @SQL
    EXEC(@SQL+' FROM TB GROUP BY 日期')(所影响的行数为 4 行)日期          点卡          直冲          
    ----------- ----------- ----------- 
    1           10          20
    2           30          40
      

  7.   

    这个sql面试经典问题啊,我也学习学习