2 my 00 my_00 于 2015.05.28 17:13 提问

SQL Server查询 一个字段中不同值在另一个字段中分别出现的总个数,总个数从打到小排序?
GoodsID  Num
A         4
B         2
C         1
A         3
B         4
C         3

我想得到:

GoodsID   Count
A          7
B          6
C          4

用SQL Server语句如何实现?恳请行家高手不吝惜指点!万分感谢!!

12个回答

caozhy
caozhy   Ds   Rxr 2015.05.28 17:25

select sum(Num) as Count, GoodsID from table group by GoodsID
2015.05.28 17:16

edouardzyc
edouardzyc   2015.05.28 17:16

select GoodsID, sum(Num) as Count from table
group by GoodsID

sjzquchen
sjzquchen 回复my_00: group by 是用来排序
2 年多之前 回复
my_00
my_00 谢谢!我如何实现按照Count中数据从大到小排序呢?
2 年多之前 回复
Tiger_Zhao
Tiger_Zhao   Rxr 2015.05.28 17:16
    SELECT GoodsID, SUM(Num) AS [Count]
      FROM table1
     GROUP BY GoodsID
     ORDER BY [Count] DESC
devmiao
devmiao   Ds   Rxr 2015.05.28 17:18

select sum(Num) as [Count], GoodsID from table group by GoodsID
order by [Count] desc
要加上方括号,Count是关键字

my_00
my_00 我的问题写上了,在我的回复里,你看见了吗?
2 年多之前 回复
my_00
my_00 回复苏小喵: 我的问题写上了,在我的回复里,你看见了吗?
2 年多之前 回复
devmiao
devmiao 回复my_00: 问啊
2 年多之前 回复
my_00
my_00 你好!在吗?我还有一个问题想请教与你,可以吗?
2 年多之前 回复
my_00
my_00 谢谢!
2 年多之前 回复
caozhy
caozhy   Ds   Rxr 2015.05.28 17:25

我的回答哪里去了。明明我第一个回答的,怎么删了?

my_00
my_00 谢谢。你是第一个回答的,谢谢。
2 年多之前 回复
jiuqiyuliang
jiuqiyuliang   2015.05.28 17:27
   SELECT GoodsID, SUM(Num) AS [Count]
      FROM table
     GROUP BY GoodsID
     ORDER BY [Count] DESC
u010223860
u010223860   2015.05.28 17:41

SELECT GoodsID, SUM(Num) AS [Count]
FROM table1
GROUP BY GoodsID
ORDER BY [Count] DESC

qq_28278709
qq_28278709   2015.05.28 19:10

SELECT GoodsID ,sum(Num) Count
FROM table
GROUP BY GoodsID
ORDER BY [Count]DESC;

my_00
my_00   2015.05.28 22:04

非常感谢大家的慷慨解答!我还有一个问题要补充:
我想从另外一个表中(GoodsInfo)获得GoodsName,和“select sum(Num) as [Count], GoodsID from OrderInfo group by GoodsID order by [Count] desc”
查询到的结果组合成一个表。如何实现呢?
两个表都有共同字段GoodsID,即实现下表所示:

GoodsID  Num
A         4
B         2
C         1
A         3
B         4
C         3

我想得到:

GoodsID   GoodsName   Count
A                         a                7
B                         b                6
C                         c                4

用SQL Server语句如何实现?恳请行家高手不吝惜指点!万分感谢!!

liuyuxuan2388
liuyuxuan2388   2015.05.28 22:08
 SELECT Sum(Num) AS Count, GoodsID FROM Table GROUP BY GoodsID
共12条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片