2017-08-17 51 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

显示时,您可以用逗号分隔字符串并打印您的预期输出。

相关问题