简体   繁体   中英

Translate MySQL query to BigQuery query

I am having trouble converting MySQL query to Google Bigquery query. This is my MySQL query

SELECT id
FROM office_details
GROUP BY address
HAVING max(value)
ORDER BY id

This query runs perfectly on phpMyAdmin and with my php script. But when I convert it to bigquery

SELECT id
FROM Office_db.office_details
GROUP BY address
HAVING max(value)
ORDER BY id

It says column id is not in group by nor aggregated.

What I need is the id s of unique address where value is maximum. eg

+-------------------------+
| id  |  address |  value |
+-------------------------+
| 1   |    a     |   4    |
| 2   |    a     |   3    |
| 3   |    b     |   2    |
| 4   |    b     |   2    |
+-------------------------+

I need

+----+
| id |
+----+
| 1  |
| 3  |
+----+
#standardSQL
SELECT id FROM (
  SELECT 
    id, address, 
    ROW_NUMBER() OVER(PARTITION BY address ORDER BY value DESC, id) AS flag
  FROM office_details
)
WHERE flag = 1

Try this:

#standardSQL
SELECT ARRAY_AGG(id ORDER BY value DESC, id LIMIT 1)[OFFSET(0)] AS id
FROM office_details
GROUP BY address;

It's less prone to running out of memory than a solution using RANK will be (and may be faster), since it doesn't need to buffer all of the rows while computing ranks within a partition. As a working example:

#standardSQL
WITH office_details AS (
  SELECT 1 AS id, 'a' AS address, 4 AS value UNION ALL
  SELECT 2, 'a', 3 UNION ALL
  SELECT 3, 'b', 2 UNION ALL
  SELECT 4, 'b', 2
)
SELECT
  address,
  ARRAY_AGG(id ORDER BY value DESC, id LIMIT 1)[OFFSET(0)] AS id
FROM office_details
GROUP BY address
ORDER BY address;

This gives the result:

address | id
------------
a       | 1
b       | 3

A valid query might look as follows:

SELECT MIN(x.id) id
  FROM office_details x
  JOIN
     ( SELECT address
            , MAX(value) value
         FROM officer_details
        GROUP 
           BY address
     ) y
    ON y.address = x.address
   AND y.value = x.value
 GROUP 
    BY address
     , value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM