我有一个订单表(order),记录用户买卖数据
id       userId      order_type     grand         city   
1          张三         买入              一等品       大连
2          张五         买入              一等品       大连
3          李四         卖出              二等品       成都
4          王五         卖出              一等品       大连
5          张飞         买入              三等品       武汉
6          武松         卖出              一等品       武汉
我现在想出一个报表, 统计每个城市的买入,卖出各个品次的数量。
我想写一句sql,产生如下统计数据,这个sql该如何写?请教CSDN的各位高人。100分附上city      order_type     grand  count
大连     买入              一等品     2
大连     买入              二等品     0
大连     买入              三等品     0
大连     卖出              一等品     1
大连     卖出              二等品     0
大连     卖出              三等品     0武汉     买入              一等品    0
武汉     买入              二等品     0
武汉     买入              三等品     1
武汉     卖出              一等品     1
武汉     卖出              二等品     0
武汉     卖出              三等品     0成都     买入              一等品    0
成都     买入              二等品     0
成都     买入              三等品     0
成都     卖出              一等品     0
成都     卖出              二等品     1
成都     卖出              三等品     0

解决方案 »

  1.   

    select  city ,order_type,grand ,count(*)
    from 订单表
    group by  city ,order_type,grand  试试看
      

  2.   

    select  city, order_type,  grand, count(grand) as counts  from order group by city, order_type,  grand  
    试试
      

  3.   

    用mssql写的,应该差不多
    --测试数据
    if not object_id(N'Tempdb..#T') is null
    drop table #T
    Go
    Create table #T([id] int,[userId] nvarchar(22),[order_type] nvarchar(22),[grand] nvarchar(23),[city] nvarchar(22))
    Insert #T
    select 1,N'张三',N'买入',N'一等品',N'大连' union all
    select 2,N'张五',N'买入',N'一等品',N'大连' union all
    select 3,N'李四',N'卖出',N'二等品',N'成都' union all
    select 4,N'王五',N'卖出',N'一等品',N'大连' union all
    select 5,N'张飞',N'买入',N'三等品',N'武汉' union all
    select 6,N'武松',N'卖出',N'一等品',N'武汉'
    Go
    --测试数据结束
    SELECT  * ,
            ( SELECT    COUNT(1)
              FROM      #T
              WHERE     city = t1.city
                        AND order_type = t2.order_type
                        AND grand = t3.grand
            ) AS count
    FROM    ( SELECT DISTINCT
                        city
              FROM      #T
            ) t1 ,
            ( SELECT DISTINCT
                        order_type
              FROM      #T
            ) t2 ,
            ( SELECT DISTINCT
                        grand
              FROM      #T
            ) t3
    ORDER BY t1.city ,
            t2.order_type ,
            t3.grand 
      

  4.   

    select a.city,a.order_type,a.grand, count(b.id)
    (
    select city,order_type,grand
    from (select distinct city from 我有一个订单表) c,(select distinct order_type from 我有一个订单表) t,(select distinct grand from 我有一个订单表) g
    ) a left join 我有一个订单表 b on a.city=b.city and a.order_type=b.order_type and a.grand=b.grand
    group by  a.city,a.order_type,a.grand