我无法将MySQL查询转换为Google Bigquery查询。这是我的MySQL查询
SELECT id
FROM office_details
GROUP BY address
HAVING max(value)
ORDER BY id
此查询在phpMyAdmin和我的php脚本上运行完美。但是当我将它转换为bigquery
时SELECT id
FROM Office_db.office_details
GROUP BY address
HAVING max(value)
ORDER BY id
它表示列id
不是分组也不是聚合。
我需要的是唯一id
的{{1}},其中address
最大。 e.g
value
我需要
+-------------------------+
| id | address | value |
+-------------------------+
| 1 | a | 4 |
| 2 | a | 3 |
| 3 | b | 2 |
| 4 | b | 2 |
+-------------------------+
答案 0 :(得分:1)
#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
答案 1 :(得分:1)
试试这个:
#standardSQL
SELECT ARRAY_AGG(id ORDER BY value DESC, id LIMIT 1)[OFFSET(0)] AS id
FROM office_details
GROUP BY address;
与使用RANK
的解决方案相比,它不太容易耗尽内存(并且可能更快),因为在计算排名时它不需要缓冲所有行在一个分区内。作为一个工作的例子:
#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;
这给出了结果:
address | id
------------
a | 1
b | 3
答案 2 :(得分:0)
有效查询可能如下所示:
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