我正在嘗試撰寫一個查詢來給我預期的結果,但我得到的結果如右圖所示
我寫了一個子查詢,計算哪些國家代碼出現了多次,但它排除了空值,這沒有給我正確的結果。有誰知道如何更改我的查詢以包含預期結果?
預期結果(左)與實際結果(右)
select ifnull(country_code,"N/A") as country_codes, continent_code
from continent_map
where country_code
IN (
SELECT country_code
from continent_map
group by country_code
having count(country_code) > 1)
order by field(country_codes,"N/A") DESC
uj5u.com熱心網友回復:
您必須IFNULL(country_code,"N/A")在任何地方使用而不是 single country_code:
SELECT IFNULL(country_code,"N/A") AS country_codes,
continent_code
FROM continent_map
WHERE IFNULL(country_code,"N/A") IN (
SELECT IFNULL(country_code,"N/A")
FROM continent_map
GROUP BY country_code
HAVING COUNT(IFNULL(country_code,"N/A")) > 1
)
ORDER BY FIELD(country_codes,"N/A") DESC
您必須保證列中"N/A"不存在country_code(或者,如果存在,則將其視為與 NULL 相同的值)。
如果列中"N/A"確實不存在,country_code那么您可以使用HAVING COUNT(*) > 1- 但這不會影響任何事情,包括性能。
uj5u.com熱心網友回復:
IN找不到 NULL。而且COUNT(NULL)是0呢。如果要計算行數,請使用COUNT(*).
最簡單的方法可能是立即用 N/A 替換 NULL:
WITH countries AS
(
SELECT COALESCE(country_code, 'N/A') AS country_code, continent_code
FROM continent_map
)
SELECT country_code, continent_code
FROM countries
WHERE country_code
IN (
SELECT country_code
FROM countries
GROUP BY country_code
HAVING COUNT(*) > 1
)
ORDER BY field(country_code, 'N/A') DESC, country_code, continent_code;
通過使用視窗函式,這是同樣的事情COUNT OVER:
SELECT country_code, continent_code
FROM
(
SELECT COALESCE(country_code, 'N/A') AS country_code,
continent_code,
COUNT(*) OVER (PARTITION BY country_code) as cnt
FROM continent_map
) counted
WHERE cnt > 1
ORDER BY field(country_code, 'N/A') DESC, country_code, continent_code;
uj5u.com熱心網友回復:
如前所述,您將編輯查詢以將 count(*) 用作 Tim。接下來要獲得頂部的空值,我們可以按如下方式排序。
select ifnull(country_code,"N/A") as country_codes, continent_code
from continent_map
where ifnull(country_code,'-1')
IN (
SELECT ifnull(country_code,'-1')
from continent_map
group by country_code
having count(*) > 1)
order by country_code is null desc,country_code asc
資料庫小提琴鏈接 https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=e76c9d4b733ca83b00067e611dbd1e80
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/407738.html
標籤:
上一篇:使用SQL過濾日期
下一篇:從動態物件生成類定義
