![](/img/trans.png)
[英]SQL: How to sum and divide values in one column based on values in another column?
[英]In SQL, how to sum numerical values in one column based on string values in another column
我希望我的程序按PlantName
返回AcceptedProducts
的PlantName
。
有人可以幫我糾正我的程序嗎?
CREATE PROCEDURE spAcceptedByCountry @Year INT, @Month INT
AS
SELECT CountryCode,
CountryName,
REPLACE(SUBSTRING([PlantName], CHARINDEX('-', [PlantName]), LEN([PlantName])), '-', '') AS [PlantName],
SUM(AcceptedProducts) AS AcceptedProducts
FROM vAcceptedByCountry
WHERE YEAR(DateOfManufacture) = @Year AND MONTH(DateOfManufacture) = @Month
GROUP BY CountryCode,
CountryName,
PlantName,
AcceptedProducts
ORDER BY CountryCode;
GO
感謝您的幫助。 親切的問候。
嘗試這個:
CREATE PROCEDURE spAcceptedByCountry @Year INT, @Month INT
AS
SELECT CountryCode,
CountryName,
REPLACE(SUBSTRING([PlantName], CHARINDEX('-', [PlantName]), LEN([PlantName])), '-', '') AS [PlantName],
SUM(AcceptedProducts) AS AcceptedProducts
FROM vAcceptedByCountry
WHERE YEAR(DateOfManufacture) = @Year AND MONTH(DateOfManufacture) = @Month
GROUP BY 1, 2, 3
ORDER BY CountryCode;
GO
您不想按您嘗試計算的聚合進行分組。
因此,現在您正在計算每個國家/地區代碼/國家/地區名稱/植物名稱的可接受產品,其中植物名稱不是列,而是選擇子句中的項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.