簡體   English   中英

組合2個SQL查詢以從一列獲取不同的值,從第二列獲得最大值

[英]Combine 2 SQL queries to get Distinct values from one column and biggest from second

我有下表:

Country Year
100 201313
100 201212
101 201314
101 201213
101 201112
102 201313
102 201212
103 201313
103 201212
104 201313
104 201212

我需要一個只提供一個國家/地區的查詢,而且只需要一年中最大的價值,例如:

Country Year
100 201313
101 201314
102 201313
103 201313
104 201313

到目前為止,我的解決方案是進行第一次查詢,其中我獲得了Distinct Countries,然后在一段時間內,另一個查詢來獲取年份......

$resOne = $mysqli->query("SELECT DISTINCT Country from Table ORDER BY Country ASC");
while ($obj = $resOne->fetch_object()){
    $resTwo = $mysqli->query("SELECT Country, Year from Table WHERE Country = $resOne->Country ORDER BY Country ASC LIMIT 1")->fetch_object();
    echo $resTwo->Country $resTwo->Year;
}

問題:僅通過一個查詢就可以提供此結果嗎?

感謝您的閱讀和回答。

UPDATE

來自user2989408和Drew的答案的腳本很好並且正常工作,但是當我加入另一個表時,我得不到正確的數據。

這是我的數據庫示例和腳本的小提琴: http//sqlfiddle.com/#!2/31613/1/0

如何使描述行顯示MAX(s.Year)中的描述? 例如,小提琴中的第一行應顯示“France newest 201314”。

你的查詢應該是

SELECT t.Country, MAX(t.Year)
FROM Table t
GROUP BY t.Country
ORDER BY t.Country ASC

編輯:更新后的要求后,要選擇其他信息,可以按如下方式修改查詢,以便工作。

SELECT c.Name, s.Description, s.Year 
FROM
    (
        SELECT s.id as id, MAX(s.Year) as Max
        FROM seasons s
        GROUP BY s.Id
    ) as X
    JOIN countries c ON c.Id = X.Id
    JOIN seasons s ON s.id = X.id AND X.Max = s.Year
ORDER BY c.Name ASC

子查詢也可用於選擇所需信息,如下所示。

SELECT c.Name,
    (SELECT s1.Description 
         FROM seasons s1 WHERE s1.id = X.id AND X.Max = s1.Year) as Description, 
    X.Max as Year
FROM
    (
        SELECT s.id as id, MAX(s.Year) as Max
        FROM seasons s
        GROUP BY s.Id
    ) as X
    JOIN countries c ON c.Id = X.Id
ORDER BY c.Name ASC

基本上,如果您了解GROUP BY工作原理,可以通過多種方式獲取所需的信息。

查詢:

SQLfiddleexample

SELECT c.Name, s.Description, s.Year
FROM countries c 
JOIN seasons s 
  ON c.Id=s.Id
LEFT JOIN seasons s2 
  ON s.ID = s2.ID
  AND s2.Year > s.Year
WHERE s2.id is null
ORDER BY c.Name ASC

結果:

|        NAME | DESCRIPTION |   YEAR |
|-------------|-------------|--------|
|      France |      newest | 201314 |
|     Germany |         new | 201212 |
|       Italy |         new | 201313 |
| Netherlands |      newest | 201313 |
|       Spain |         new | 201313 |
SELECT         Country, 
               Max(Year) 
FROM   Table 
GROUP  BY Country 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM