1

我有这样的mysql查询的表事务。

 ____________________________________________________________
 | id | noskom      | nonpbm     |    noskop   |    npbp     |
 |____|_____________|____________|_____________|_____________|
 |  1 | 001         |   10       |       20    |       20    |
 |  2 | 001         |   20       |       10    |       20    |
 |  3 | 002         |    5       |       10    |       20    |
 |  4 | 003         |   30       |        5    |       20    |
 |____|_____________|____________|_____________|_____________|

我想要结果

 select sum(nonpbm),sum(noskop),sum(npbp) from transaction group by noskom

 ____________________________________________________________
 | id | noskom      | nonpbm     |    noskop   |    npbp     |
 |____|_____________|____________|_____________|_____________|
 |  1 | 001         |   30       |       30    |       40    |
 |  2 |             |            |             |             |
 |  3 | 002         |    5       |       10    |       20    |
 |  4 | 003         |   30       |        5    |       20    |
 |____|_____________|____________|_____________|_____________|

什么是mysql查询

4

3 回答 3

2
SELECT 
    noskom , 
    SUM(nonpbm) as nonpbm , 
    sum(noskop) as noskop , 
    sum(npbp) as  npbp
FROM mytable 
GROUP BY noskom 

如果要列出对聚合值有贡献的所有行的 ID,还可以添加此列:

GROUP_CONCAT(id ORDER BY id) AS id

这将为您提供一个以逗号分隔的 ID 列表。您可以指定不同的分隔符,例如 EOL:

GROUP_CONCAT(id ORDER BY id SEPARATOR '\r\n') AS id

'\r\n'是 Windows 世界中的标准行分隔符。更改为 just'\n''\r'如果您在不同的平台上。

于 2012-12-20T07:59:49.333 回答
1
select transaction.id,t.noskom,t.sum_nonpbm,t.sum_noskop,t.sum_npbp
from transaction
left join 
(
   select noskom, min(id) min_id, 
               sum(nonpbm) sum_nonpbm,
               sum(noskop) sum_noskop,
               sum(npbp) sum_npbp 
   from transaction 
   group by noskom
) t on (transaction.id=t.min_id)
order by transaction.id
于 2012-12-20T08:23:57.660 回答
1

试试这个查询::

select tbl2.id,tbl1.noskom,tbl1.sum1,tbl1.sum2,tbl1.sum3 from
(select id,noskom,sum(nonpbm) sum1,sum(noskop) sum2,sum(npbp) sum3 from tbl group by noskom) tbl1
 right join
(select id,null a,null b,null c,null d
from tbl) tbl2
on tbl1.id = tbl2.id
order by 1 ;
于 2012-12-20T08:42:23.180 回答