客户去商店买东西,每个商品都有一个Type_ID表结构如下
table1(表名)
ID(客户)   type_ID(商品) 
1            1
2            1
2            2
1            2
3            1
1            3
。           。
。           。
实现查询结果如下
ID  type_id   type_id   type_ID
1      1         2         3
2      1         2
3                            3
实现在每个人都买啦什么产品

解决方案 »

  1.   

    假设有张学生成绩表(CJ)如下
    Name Subject Result
    张三 语文 80
    张三 数学 90
    张三 物理 85
    李四 语文 85
    李四 数学 92
    李四 物理 82想变成 
    姓名 语文 数学 物理
    张三 80 90 85
    李四 85 92 82declare @sql varchar(4000)
    set @sql = 'select Name'
    select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result end) ['+Subject+']'
    from (select distinct Subject from CJ) as a
    select @sql = @sql+' from test group by name'
    exec(@sql)
      

  2.   

    如果是B:每个人买了多少次某产品,你可以这样做,用纯sql。
    select id, sum(CTypeID3),sum(CTypeID3),sum(CTypeID3)
    from 
    (
    (select id,count(TypeID1) as CTypeID1,CTypeID2=0,CTypeID3=0
    from Table1
    where TypeID=1
    group by id)
    union
    (
    select id,CTypeID1=0,count(TypeID2) as CTypeID2,CTypeID3=0
    from Table1
    where TypeID=2
    group by id
    )
    union
    (
    select id,CTypeID1=0,CTypeID2=0,count(TypeID3) as CTypeID3
    from Table1
    where TypeID=3
    group by id
    )
    ) as TempTT
    group by id
      

  3.   

    利用sql中,重要的CASE方法:
    一、表结构:
    ID type_ID
    u1 p1
    u1 p2
    u2 p3
    u3 p3
    u4 p4
    u5 p4
    u6 p4
    u7 p5
    u8 p5
    u8 p4
    u5 p3

    二、SQL语句:
    SELECT id
    ,max(case when type_id='p1' then type_id else '' end) as p1
    ,max(case when type_id='p2' then type_id else '' end) as p2
    ,max(case when type_id='p3' then type_id else '' end) as p3
    ,max(case when type_id='p4' then type_id else '' end) as p4
    ,max(case when type_id='p5' then type_id else '' end) as p5
    FROM products
    group by id三、结果:
    id p1 p2 p3 p4 p5
    ----------------------------------------------
    u1 p1 p2
    u2 p3
    u3 p3
    u4 p4
    u5 p3 p4
    u6 p4
    u7 p5
    u8 p4 p5
      

  4.   

    楼上的方法虽可以实现,但有没有考虑过如果数据笔数较多,这样一条条的 max case ,人会疯掉的