问题
I'm sorry the TITLE is not so specific. I'll try to explain: I'm new to SQL. I'm at work and wrote a query which has 9 columns that takes information out of many tables. on the 9th column are names of types of machines, on the 3rd are value representing the time a machine worked in a month. I need to add a 10th column which will have for each type of machine, the maximum of 3rd columns for this type. lets say there are 5 machines of type XR (5 rows in the table) with times (3rd column) of 1,2,3,4,5 (in hours). I need that on the 10th column, all rows where type of machine is XR will have the value 5, as it is the maximum for this type of machine.
How do i do that?
Any help would be very appreciated!!
回答1:
In SQL Server, Oracle and PostgreSQL:
SELECT *, MAX(col3) OVER (PARTITION BY col9)
FROM mytable
In MySQL:
SELECT mt.*, maxcol3
FROM (
SELECT col9, MAX(col3) AS maxcol3
FROM mytable
) q
JOIN mytable mt
ON mt.col9 = q.col9
来源:https://stackoverflow.com/questions/10412033/in-sql-how-to-aggregate-on-a-field-inside-the-table