我下面的这组数据,是我根据这段sql查询出来的
select b.superId,b.createTime,b.totalMoney  from tb_months a ,(
select  sum(o.total_money) as totalMoney,month(o.create_time) as createTime,a.superid as superId ,a.address  as address from 
tb_order o,tb_address a where o.address_id=a.address_id and year(create_time)=YEAR(NOW())
 group by month(create_time),superid
)b where a.monthes=b.createTime 
结果:
superId createTime totalMoney
ad006 1 200
ad006 2 80
ad006 3 30
ad006 4 70
ad006 5 300
ad008 6 200
ad008 7 70
ad006 10 50
ad008 10 345
ad006 11 20
ad013 11 100
ad013 12 100createTime 为月份,然后我现在需要的是,把id分组列出1-12月份的信息,没有的用0补足。要显示的结果如下:
id   months totalMoney
ad006 1 200
ad006 2 80
ad006 3 30
ad006 4 70
ad006 5 300
ad006   6       0
ad006   7       0
ad006   8       0
ad006   9       0
ad006 10 50
ad006 11 20
ad006   12      0
ad008 1 0
ad008 2 0
ad008 3 0
ad008 4 0
ad008 5 0
ad008 6 200
ad008 7 70
ad008 8 0
ad008 8 0
ad008 10 345
ad008 11 0
ad008 12 0
ad013 1 0
ad013 2 0
ad013 3 0
ad013 4 0
ad013 5 0
ad013 6 0
ad013 7 0
ad013 8 0
ad013 9 0
ad013 10 0
ad013 11 100
ad013 12 100

解决方案 »

  1.   

    生成有1-12内容的临时表LSB,字段ID,与你的查询连接
    你的查询:存为VIEW1
    SELECT id,months,SUM(totalMoney) FROM (
    SELECT * FROM VIEW1
    UNION ALL
    SELECT A.id,B.ID,0 FROM LSB B,(select DISTINCT id FROM VIEW1) A) C
    GROUP BY id,months
      

  2.   

    我的tb_months表里,就是存的1-12呢,应该就不用去建临时表了吧。
      

  3.   

    是啊,我的意思就我的tb_months表不就相当于你说的临时表了,因为这个表里就只有一个字段,值就是1-12。还有就是,你说把我查询出来的存为view1是啥意思啊,我用我的查询出现有数据来的那段sql代替views1去查,是在报错的额,能否详细讲解下,我不太清楚。
      

  4.   

    select * from tb_months b,
    (select dictinct superId from atb_address )a
    union all
    select * from (
    select  sum(o.total_money) as totalMoney,month(o.create_time) as createTime,a.superid as superId ,a.address  as address from 
     tb_order o,tb_address a where o.address_id=a.address_id and year(create_time)=YEAR(NOW())
      group by month(create_time),superid
     )b1对UNION的结果再求和,自行修改2个SQL语句返回的字段
      

  5.   

    第一条查询语句出来的结果是两个字段,b.monthes,a.superId,然后第二条查询语句返回的结果是可以有四个字段,b1.totalMoney,b1.createTime,b1.superId ,b1.address 然后用union all的话,是两个查询语句要返回的字段个数是一样的,所以我在后面四个字段也取两个就不报错,但是这样查询出来的结果页是不对的额