In SQL, how to aggregate on a field inside the table

依然范特西╮ 提交于 2019-12-12 14:59:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!