[英]How do I group by on calculated columns?
Assume the following table with 3 numeric fields:假设下表有 3 个数字字段:
Images (table)
--------------
Width
Height
Amount
Width and Height are image sizes in millimeters.宽度和高度是以毫米为单位的图像大小。 Now I want to create a report about the amount of images grouped by their dimensions in centimeters.现在我想创建一个关于按厘米尺寸分组的图像数量的报告。 This means that I have to GROUP BY 2 non existing columns.这意味着我必须对 2 个不存在的列进行 GROUP BY。
I can do:我可以:
SELECT ROUND(Width/10,0) AS W
, ROUND(Height/10,0) AS H
, SUM(Amount) AS A
FROM IMAGES
GROUP BY Width
, Height
ORDER BY W
, H
, A
but this will do the mm to cm conversion only on the view level and will result in more than one row for same dimensions.但这只会在视图级别进行毫米到厘米的转换,并且会导致相同尺寸的多行。
eg例如
W H A
--- --- -
150 159 2
150 160 1
will not result in 1 category不会导致 1 个类别
W H A
-- -- -
15 16 3
but in但在
W H A
-- -- -
15 16 2
15 16 1
The targeted engine is actually a FileMaker database, that unfortunatly does not seem to support aggregate functions within the GROUP BY clause.目标引擎实际上是一个 FileMaker 数据库,遗憾的是它似乎不支持 GROUP BY 子句中的聚合函数。
Simply GROUP BY
your calculated columns:简单GROUP BY
您的计算列:
SELECT
ROUND(Width/10,0) as W
,ROUND(Height/10,0) as H
,COUNT(*) as A -- You may replace this with SUM(Amount) too
FROM
IMAGES
GROUP BY
ROUND(Width/10,0)
,ROUND(Height/10,0)
ORDER BY
W
,H
,A
EDIT: Also, from what I understand of your question you want the COUNT
not the SUM
of the rows..., right?编辑:另外,根据我对你的问题的理解,你想要的是COUNT
而不是行的SUM
......,对吧?
Following query uses Common Table Expression (CTE)
to convert width and height from mm to cm along with rounding and then produces a derived table output.以下查询使用Common Table Expression (CTE)
将宽度和高度从 mm 转换为 cm 并进行舍入,然后生成派生表输出。 This CTE output is then used to group the width and height values to calculate the SUM of the amount column.然后使用此 CTE 输出对宽度和高度值进行分组,以计算数量列的总和。
I am not sure if you were looking for SUM
of the amount column or the COUNT
of the amount column.我不确定您是在查找金额列的SUM
还是金额列的COUNT
。 I assumed SUM based on your query.我根据您的查询假设了SUM 。 If you only want COUNT , please change SUM in the query to COUNT .如果您只想要COUNT ,请将查询中的SUM更改为COUNT 。
Click here to view the demo in SQL Fiddle单击此处查看 SQL Fiddle 中的演示
Script :脚本:
CREATE TABLE images
(
width INT NOT NULL
, height INT NOT NULL
, amount FLOAT NOT NULL
);
INSERT INTO images (width, height, amount) VALUES
(150, 159, 1),
(150, 159, 2),
(150, 158, 1),
(150, 159, 3),
(150, 158, 2),
(160, 158, 4),
(160, 158, 1);
;WITH imagesincm AS
(
SELECT ROUND(width / 10,0) AS W
, ROUND(height / 10,0) AS H
, amount
FROM images
)
SELECT W
, H
, COUNT(amount) AS A
FROM imagesincm
GROUP BY W
, H
ORDER BY W
, H
Output :输出:
W H A
-- -- -
15 15 9
16 15 5
根据官方 FileMaker SQL 参考 ( https://help.claris.com/en/sql-reference.pdf ) 的第 11 页,Group By 子句仅适用于字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.