大家好我正在讨论为我的案例陈述总结saleytd的问题。我已经尝试在SalesYTD前放置一个sum函数,我得到的错误是sales旁边的synthax错误。我也尝试过salesytd进行分组,但这不起作用,因为它给了我这个错误列'PERSON.STATEPROVINCE.StateProvinceID'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。在这里我的查询如下。我的查询工作正常我只是得到它总和我的总数。
USE AdventureWorks2014;
GO
SELECT STATEPROVINCEID,A.NAME,A.COUNTRYREGIONCODE,(b.SALESYTD),
CASE
WHEN A.TerritoryID = '1' THEN 'WESTERN MARKET'
WHEN A.TerritoryID = '2' THEN 'NORTH EASTERN MARKET'
WHEN A.TerritoryID = '3' THEN 'MID WESTERN MARKET'
WHEN A.TerritoryID = '4' THEN 'SOUTH WESTERN MARKET'
WHEN A.TerritoryID = '5' THEN 'SOUTH EASTERN MARKET'
ELSE 'OTHER'
END AS MARKET
FROM PERSON.STATEPROVINCE as A INNER JOIN SALES.SalesTerritory AS B
ON A.TerritoryID = B.TerritoryID
WHERE A.CountryRegionCode = 'US'
答案 0 :(得分:0)
如果您只想了解西南市场迄今为止的总销售年度,那么您可以针对该市场的SALESYTD
列进行条件汇总:
SELECT SUM(CASE WHEN A.TerritoryID = '4' THEN b.SALESYTD ELSE 0 END) AS total_sales
FROM PERSON.STATEPROVINCE a
INNER JOIN SALES.SalesTerritory b
ON a.TerritoryID = b.TerritoryID
WHERE a.CountryRegionCode = 'US'
如果您想要所有地区的总和,那么您可以使用GROUP BY
:
SELECT a.TerritoryID, SUM(b.SALESYTD) AS total_sales
FROM PERSON.STATEPROVINCE a
INNER JOIN SALES.SalesTerritory b
ON a.TerritoryID = b.TerritoryID
WHERE a.CountryRegionCode = 'US'
GROUP BY a.TerritoryID
答案 1 :(得分:0)
我终于把一切都搞定了。感谢大家。这是我的查询
SELECT SUM(b.SALESYTD) AS TOTALSALES,
case
when a.TerritoryID = '1' then 'WESTERN MARKET'
WHEN A.TERRITORYID = '2' THEN 'NORTH EASTERN MARKET'
when a.TerritoryID = '3' then 'MID WESTERN MARKET'
WHEN A.TerritoryID = '4' THEN 'SOUTH WESTERN MARKET'
WHEN A.TERRITORYID = '5' THEN 'SOUTH EASTERN MARKET'
else 'OTHER'
end as MARKETS
FROM PERSON.STATEPROVINCE a
INNER JOIN SALES.SalesTerritory b
ON a.TerritoryID = b.TerritoryID
WHERE a.CountryRegionCode = 'US'
GROUP BY a.TerritoryID