你們能告訴我如何根據列值(訂單、大陸和國家)進行輸出金額總和的查詢嗎?另外,我想將所有大陸價值顯示為獨特價值(北美)
示例表,
ID Code Continent Country amount
----------------------------------------------------
1 1 North America NULL NULL
2 1 America USA 10
3 1 NA USA 10
4 1 Unknown USA 10
5 2 North America NULL NULL
6 2 America Canada 15
7 2 NA Canada 15
8 2 Unknown Canada 15
9 3 North America NULL NULL
10 3 America Mexico 20
11 3 NA Mexico 20
12 3 Unknown Mexico 20
輸出
ID Code Continent Country SumAmount
----------------------------------------------
1 1 North America USA 30
2 2 North America Canada 45
3 3 North America Mexico 60
我試圖接近它
select ID, Code, case when Continent != 'North America' then Continent = 'North America' end as Continent, Country, sum(Amount) as SumAmount
from Table group by ID, Continent, Country
或者也許我需要進行這樣的查詢并使用下面的查詢?
select ID, Code, Continent, Country, sum(Amount) as SumAmount
from Table where Continent !='North America'
但它不起作用。我該怎么做?
我感謝任何其他方法。會比我的好
uj5u.com熱心網友回復:
這里笨拙的設計(除了共享Code列之外沒有真正指示的關系)將導致像這樣的次優查詢
DECLARE @ContinentToReport varchar(32) = 'North America';
;WITH x AS
(
SELECT Code FROM dbo.TableName
WHERE Continent = @ContinentToReport
AND Country IS NULL
)
SELECT ID = ROW_NUMBER() OVER (ORDER BY x.Code),
x.Code,
Continent = @ContinentToReport,
t.Country,
SumAmount = SUM(t.amount)
FROM dbo.TableName AS t
INNER JOIN x ON t.Code = x.Code
WHERE t.Country IS NOT NULL
GROUP BY x.Code, t.Country
ORDER BY x.Code;
輸出(雖然我猜測了ID它的含義以及為什么它ID與源代碼不同,但我發現該Continent列有點多余,因為它總是相同的):
| ID | 代碼 | 大陸 | 國家 | 金額 |
|---|---|---|---|---|
| 1 | 1 | 北美 | 美國 | 30 |
| 2 | 2 | 北美 | 加拿大 | 45 |
| 3 | 3 | 北美 | 墨西哥 | 60 |
- 示例db<>fiddle
uj5u.com熱心網友回復:
您的一般設計有一些可以改進的地方,但您可以通過以下查詢來完成它:
select 'North America' Continent
, t.Country
, sum(t.amount) sumAmount
from table
where t.Country is not null
group by t.Country
您將無法根據ID需要進行分組選擇,這會破壞您的數學。由于您只希望所有Continents 都是北美,因此您可以輸入一個靜態值。
但是,我認為您正在尋找分組Order而不是ID. 你可以這樣做:
select t.[Order]
, 'North America' Continent
, t.Country
, sum(t.amount) sumAmount
from t
where t.Country is not null
group by t.[Order], t.Country
order by t.[Order]
Continent再次,我建議改變表格設計,如果你總是想成為北美,你可能需要考慮改變做法。如果你將來改變主意怎么辦?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/418512.html
標籤:
上一篇:以下資料輸入的SQL查詢
下一篇:使用STE更新記錄
