我正在开发一个 API 来返回建筑项目列表。
SELECT
`sample`.`Development Type` AS 'Development Type',
`sample`.`Postcode` AS 'Postcode',
`sample`.`Value Desc` AS 'Value Desc'
FROM
`sample`
WHERE `sample`.`Postcode` LIKE '%SW1%'
这会返回一个建筑项目列表。
Development Type | Postcode | Value Desc
Refurbishment & Extension | SW1E 6LB | 400,000
Refurbishment & Extension | SW1E 6LB | 400,000
Refurbishment & Extension | SW1X 8AL | 75,000
Refurbishment & Extension | SW1X 8AL | 75,000
Refurbishment & Extension | SW1P 3RE | 225,000
Refurbishment & Extension | SW1P 3RE | 225,000
Extension | SW1X 7QU | 200,000
Extension | SW1X 7QU | 200,000
Refurbishment | SW1X 8AL | 75,000
我需要修改查询以获得这样的输出。
Development Type | Sum Value Desc
Refurbishment & Extension | 700,000
Extension | 200,000
Refurbishment | 75,000
--所以按开发类型分组--删除重复的结果(可能是我应该做一个 where 查询的标志,以千为单位求和以处理逗号)
最佳答案
这将是一个简单的 GROUP BY
查询,如果不是因为每条记录似乎重复出现的话。但这可以通过首先使用带有 SELECT DISTINCT
的子查询来删除重复项,然后从此子查询分组以获得所需的总和来解决:
SELECT t.`Development Type`, FORMAT(SUM(t.`Value Desc`), 0)
FROM
(
SELECT DISTINCT `Development Type`, `Postcode`, `Value Desc`
FROM sample
) t
GROUP BY t.`Development Type`
ORDER BY SUM(t.`Value Desc`) DESC
点击下面的链接获取正在运行的演示:
SQLFiddle
更新:
由于您的源数据可能是 CSV 格式,您可以将外部 SELECT
语句更改为以下内容以处理逗号:
SELECT t.`Development Type`,
FORMAT(SUM(CAST(REPLACE(`Value Desc`, ',' , '') AS UNSIGNED)), 0)
您还可以将 ORDER BY
子句更改为:
ORDER BY SUM(CAST(REPLACE(`Value Desc`, ',' , '') AS UNSIGNED)) DESC
关于mysql - SQL按开发类型分组和值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39001696/