我有一张看起来像这样的表:
ComputerID | Free_Space | Disk_Size
------------------------------------------
Computer1 | 10 | 15
Computer1 | 10 | 10
Computer1 | 05 | 10
Computer2 | 05 | 05
Computer2 | 05 | 10
Computer3 | 11 | 15
Computer3 | 04 | 05
我需要实现这样的目标:
ComputerID | Free_Space | Disk_Size
------------------------------------------
Computer1 | 25 | 35
Computer2 | 10 | 15
Computer3 | 15 | 20
我尝试过这样的事情,但没有成功。
SELECT ComputerID,
SUM(free_space/1000000000) AS 'Total Free Space',
SUM(disk_size/1000000000) AS 'Total Size'
FROM myTable
ORDER BY ComputerID
非常感谢任何帮助。
答案 0 :(得分:3)
SELECT ComputerID,
SUM(free_space/1000000000) AS 'Total Free Space',
SUM(disk_size/1000000000) AS 'Total Size'
FROM myTable
GROUP BY ComputerID
答案 1 :(得分:2)
要实现您现在提出的问题,只需执行以下操作:
SELECT ComputerID,
SUM(free_space) AS 'Total Free Space',
SUM(disk_size) AS 'Total Size'
FROM myTable
GROUP BY ComputerID
如果值以字节为单位并且您希望以gb显示它们,请执行以下操作:
SELECT ComputerID,
SUM(free_space/1073741824) AS 'Total Free Space',
SUM(disk_size/1073741824) AS 'Total Size'
FROM myTable
GROUP BY ComputerID
答案 2 :(得分:1)
使用与非聚合字段(computerid)混合的聚合函数(例如sum())的任何查询都必须使用group by子句:
SELECT ...
FROM ...
GROUP BY ComputerID
ORDER BY ...
答案 3 :(得分:0)
您需要GROUP BY子句
SELECT
ComputerID,
SUM(free_space/1000000000) AS "Total Free Space",
SUM(disk_size/1000000000) AS "Total Size"
FROM
myTable
GROUP BY
ComputerID
ORDER BY
ComputerID
另请注意,大多数SQL方言使用单引号作为字符串分隔符,使用双引号作为列名称的分隔符。使用SQL Server,您还可以使用方括号
[Total Free Space]
。