答案 0 :(得分:1)
SELECT r.Region_Name, SUM(s.Sales) Sales,
CASE WHEN COUNT(g.Store_Name) > 0 THEN 'Y' ELSE 'N' END Stores
FROM (SELECT DISTINCT Region_name FROM Geography) r
LEFT JOIN Geography g ON g.Region_Name = r.Region_Name
LEFT JOIN Store_Information s ON s.Store_Name = g.Store_Name
GROUP BY r.Region_Name
答案 1 :(得分:1)
注意:在你的问题中你没有提到数据库,所以我在SQL Server版本中添加了这个不适合MySQL的查询。我删除了问号[sql-server]
。
这是您的代码(SQL Server版本)
SELECT GE.[RegionName] AS [Region_Name]
,ISNULL(SUM (SI.[NetSales]), 0) AS [NetSales]
,CASE WHEN SUM (SI.[NetSales]) IS NULL THEN N'N' ELSE N'Y' END AS [Stores]
FROM [DevDB].[dbo].[Geography] GE
LEFT JOIN (SELECT StoreName, SUM([Sales]) AS [NetSales]
FROM [DevDB].[dbo].[Store_Information]
GROUP BY StoreName) SI
ON SI.[StoreName] = GE.[StoreName]
GROUP BY GE.[RegionName]
<强>输出强>:
答案 2 :(得分:1)
假设这是SQL Server,而Sales是NVARCHAR
列。
SELECT DISTINCT
[Region_name],
ISNULL('$' + CAST(SUM(CAST(Sales as MONEY)) AS NVARCHAR(20)), '$0') Sales,
CASE WHEN SUM(CAST(Sales as MONEY)) > 0
THEN 'Y'
ELSE 'N'
END Stores
FROM Geography geo
LEFT JOIN Store_Information sto ON sto.Store_Name = geo.Store_name
GROUP BY [Region_name]
答案 3 :(得分:1)
在MYSQL中,您可以通过left join-ing
store_info
与geography
表和group by
列Region
获得结果,如下所示。您不需要SUM
再次单独CASE
。
SELECT g.region,
sum(s.Sales) AS Sales,
CASE
WHEN Sales > 0 THEN 'Y'
ELSE 'N'
END AS Stores
FROM geography g
LEFT JOIN store_info s ON s.SN = g.SN
GROUP BY g.Region
ORDER BY 2 DESC
<强>结果强>
region Sales Stores
----------------------
West 2050 Y
East 700 Y
South NULL N
North NULL N
您可以查看演示here
希望这会有所帮助。