如果列的特定值出现多次,如何检入SQL

时间:2017-08-24 04:02:55

标签: mysql sql group-by

我正在尝试这个问题,我遇到了SUM特定区域的销售情况,然后需要根据名称stores创建另一个列,以便它可以判断该特定商店是否在该地区(东,西,北和南)。

我不知道从哪里开始 这些是两个表和输出: enter image description here

4 个答案:

答案 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]

<强>输出

enter image description here

答案 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_infogeography表和group byRegion获得结果,如下所示。您不需要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

希望这会有所帮助。