我在SQL server中有一个像附加图像的表。
我正在尝试根据SUM(freight)
列检索已排序的数据。为此,我使用了以下查询。
SELECT ShipCountry
FROM CountryDetails
GROUP BY ShipCountry
ORDER BY SUM(freight) ASC
当我运行这个时,我得到的结果如下。
如果我运行以下查询,我会得到如下结果。没关系。
SELECT ShipCountry, ShipCity
FROM CountryDetails
GROUP BY ShipCountry, ShipCity
ORDER BY SUM(Freight), ShipCity ASC
而不是这个,我需要一个像下面这样的结果。按照SUM(Freight)
条款的顺序,只应考虑ShipCountry
。它不应该同时考虑ShipCountry
和ShipCity
。我的预期结果是
如何通过SQL查询实现此结果?
答案 0 :(得分:1)
您可以尝试下面的查询
select
ShipCountry,
ShipCity
from
(
Select
ShipCountry,
ShipCity,
SUM(Freight) OVER( Partition by ShipCountry order by ShipCountry) NetCountry,
SUM(Freight) OVER( Partition by ShipCountry,ShipCity order by ShipCountry) NetCity
from
CountryDetails
) T
Order by NetCountry asc,ShipCity asc
<强> Live Demo 强>
答案 1 :(得分:0)
我认为CUBE
或ROLLUP
会帮助您获得结果。但请查看我创建的下面的查询。我刚刚从你分享的模型中创建了查询。我无法保证表现。另外,请省略第一列和最后一列。
;
WITH CTE_ShipDetails1
AS (
SELECT ShipCountry
, MIN(ShipCity) ShipCity
, SUM(Freight) NetCity
, 0 RowNum
FROM CountryDetails
GROUP BY ShipCountry
)
, CTE_ShipDetails2
AS
(
SELECT CTE1.ShipCountry ShipCountry1
, NULL ShipCountry
, CountryDetails.ShipCity
, ROW_NUMBER() OVER (
ORDER BY CTE1.ShipCountry
, CTE1.ShipCity
) RowNum
, SUM(Freight) OVER(PARTITION BY CountryDetails.ShipCountry, CountryDetails.ShipCity) NetCity
FROM CountryDetails
, CTE_ShipDetails1 CTE1
WHERE CTE1.ShipCountry = CountryDetails.ShipCountry
AND CTE1.ShipCity <> CountryDetails.ShipCity
)
SELECT DISTINCT ShipCountry1, ShipCountry
, ShipCity, NetCity, MIN(RowNum) RowNum
FROM
(
SELECT TOP 250000 ShipCountry ShipCountry1, ShipCountry
, ShipCity, NetCity, RowNum
FROM CTE_ShipDetails1 CTE1 UNION
SELECT TOP 250000 ShipCountry1, ShipCountry
, ShipCity, NetCity, RowNum
FROM CTE_ShipDetails2 CTE2
) AS a GROUP BY ShipCountry1, ShipCountry
, ShipCity, NetCity
ORDER BY ShipCountry1 ASC
, RowNum ASC
;