Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I group by on calculated columns?

Tags:

sql

group-by

Assume the following table with 3 numeric fields:

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.

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.

e.g.

 W   H  A
--- --- - 
150 159 2
150 160 1

will not result in 1 category

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.

like image 629
mselbach Avatar asked May 01 '12 14:05

mselbach


People also ask

Can I GROUP BY calculated field?

You can't use Groups in calcs--but if you use a calculated field to create the groups, you could use that. It depends how you created the group. If you used the paperclip icon in Tableau or a right-click and Group, you cannot reference this value in a calculation.

How do you group a calculated field in tableau?

Create a group from a field in the Data paneIn the Data pane, right-click a field and select Create > Group. In the Create Group dialog box, select several members that you want to group, and then click Group.

How do I GROUP BY value in a column?

Group a column by using an aggregate function For more information see Create, edit, and load a query in Excel. Select Home > Group by. In the Group by dialog box, select Advanced to select more than one column to group by.

How does GROUP BY works on multiple columns?

The GROUP BY clause is used along with some aggregate functions to group columns with the same values in different rows. The group by multiple columns technique retrieves grouped column values from one or more database tables by considering more than one column as grouping criteria.


1 Answers

Simply GROUP BY your calculated columns:

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?

like image 99
Matthew Avatar answered Nov 11 '22 08:11

Matthew