用SQL按两个字段分组查询

来源:百度知道 编辑:UC知道 时间:2024/05/21 06:27:34
目前存在这样一张表:
month no money
2003 1 100
2003 1 400
2003 2 200
2004 1 100
2004 3 500
2005 1 100
2005 2 300
2005 3 400
2005 3 100
我需要查询的结果是这样的:
2003 1 500
2 200
3 0
2004 1 100
2 0
3 500
2005 1 100
2 300
3 500
也就是查询每年3个no对应的money的和,想了好久也弄不出来,谁可以告诉我如何写SQL语句,感激不尽!
我把需要的结果完善一下
2003 1 500
2003 2 200
2003 3 0
2004 1 100
2004 2 0
2004 3 500
2005 1 100
2005 2 300
2005 3 500
如果可以,最好排这样,这是我最终要的结果,高手请看(斜杠是我用来帮助区分开数据的,当不存在就行):
m-n /1 /2 /3
2003 /500 /200 /0
2004 /100 /0 /500
2005 /100 /300 /500

SELECT month,no,money=SUM(MONEY) FROM TABLENAME GROUP BY MONTH,NO ORDER BY MONTH,NO
上面是第一个结果。

第二个这样得到:
select month as [m-n],
(select sum(money) from tablename b where b.month=a.month and b.no=1) as [1],
(select sum(money) from tablename b where b.month=a.month and b.no=2) as [2],
(select sum(money) from tablename b where b.month=a.month and b.no=3) as [3]
from
(select distinct month from tablename) a

select month, no,sum(money) money from [表名]
GROUP BY month ,no
这样查的结果中,没有2003 3 和2004 2
的结果.因为表中没有记录

用下面试试
Select month,sum((1-abs(sign(no-1)))*money 1, sum((1-abs(sign(no-2)))*money 2, sum((1-abs(sign(no-3)))*money 3
From [表名] GUOUP BY month

如果money字段不是money类型,转换一下

Select month,convert(money,sum((1-abs(sign(no-1)))*money) 1, convert(money,sum((1-abs(sign(no-2)))*money) 2, convert(money,sum((1-abs(sign(no-3)))*money) 3
From [表名] GUOUP BY month

select A.[mon