我正在研究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
- 所以按开发类型分组 - 删除重复的结果(可能是我应该在查询时执行的标记,总计数千来处理逗号)
答案 0 :(得分:1)
如果不是因为每个记录似乎重复出现,这将是一个简单的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
请按照以下链接查看正在运行的演示:
<强>更新强>
由于您的源数据可能是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