2017-08-17 24 views
0

我有一個像MySQL數據庫中附加圖像的表。基於MySQL中的一個數字列檢索排序的數據

MySQL table

我試圖找回基於SUM(貨運)列排序的數據。爲此,我使用了下面的查詢。

SELECT貨主國家 FROM CountryDetails GROUP BY貨主國家 ORDER BY SUM(貨運)ASC

當我運行此我得到的結果如下圖所示。

MySQL result

如果我運行下面的查詢我得到的結果如下圖所示。沒關係。

SELECT貨主國家,貨主國家 FROM CountryDetails GROUP BY貨主國家,貨主國家 ORDER BY SUM(貨運),貨主國家ASC

Results

取而代之的是我需要一個像下面的結果。按條款順序SUM(Freight)應僅考慮ShipCountry。它不應該考慮ShipCountry和ShipCity。我的預期結果是

Tableau's result

如何實現通過MySQL查詢這樣的結果?

在SQL中我們可以實現如下查詢。

從ShipCountry中選擇ShipCountry,ShipCity來自Countrydetails組,ShipCity通過SUM(SUM(貨運))對(由ShipCountry進行劃分),Shipcity Asc。

我們需要在MySQL中這樣的等效查詢。

回答

1

試試這個:

SELECT t1.ShipCountry, t1.ShipCity, t2.countrysum FROM CountryDetails t1 
    join (select ShipCountry, SUM(freight) countrysum from CountryDetails 
     group by ShipCountry) 
    as t2 on t1.ShipCountry = t2.ShipCountry 
GROUP BY ShipCountry, ShipCity 
ORDER BY countrysum ASC ; 

它包含一個子查詢,但應爲每個國家的城市對單獨的一行。

+0

是的。上述查詢產生我的預期結果。謝謝你的幫助。 –

1

您可以GROUP BY ShipCountryGROUP_CONCAT城市如下

SELECT 
    ShipCountry, 
    GROUP_CONCAT(ShipCity ORDER BY ShipCity ASC) AS cities, 
    SUM(freight) AS total_country_freight 
FROM 
    Countrydetails 
GROUP BY 
    ShipCountry 
ORDER BY 
    total_country_freight ASC 

這將輸出

阿根廷|布宜諾斯艾利斯

西班牙|波特蘭

挪威| Butte,Stavern

意大利| Albuquerque

葡萄牙| Lisboa

波蘭| Elgin,Seattle,Walla Walla,Warszawa

顯示時,您可以用逗號分隔字符串並打印您的預期輸出。

相關問題