【问题标题】:SQL count items outside of group by filterSQL按过滤器计算组外的项目
【发布时间】:2015-07-06 06:43:51
【问题描述】:

假设我有下表:

Product A    Product B
Water        Soda
Water        Soda
Water        Eggs
Water        Apples

我正在尝试计算产品组合和每种产品的数量,以便我的结果是:

Product A   Product B   Combination Product A Count Product B Count
Water        Soda               2                 4               2
Water        Eggs               1                 4               1
Water        Apples             1                 4               1

不幸的是,一旦我对产品进行分组,我就无法获得单个计数。任何帮助,将不胜感激。

SELECT [ProductA], [ProductB], Count(*) as ComboCount
FROM [ProductCombinations]
GROUP BY [ProductA], [ProductB]
Order by ComboCount Desc

【问题讨论】:

    标签: sql sql-server select count group-by


    【解决方案1】:

    您可以单独计算每个产品,并将它们加入您当前的查询:

    SELECT   p.[ProductA], p.[ProductB], COUNT(*) As CombotCount, 
             ProductA_Count, ProductB_Count
    FROM     [ProductCombinations] p
    JOIN     (SELECT   [ProductA], COUNT(*) AS ProductA_Count
              FROM     [ProductCombinations]
              GROUP BY [ProductA]) a ON p.[ProductA] = a.[ProductA]
    JOIN     (SELECT   [ProductB], COUNT(*) AS ProductB_Count
              FROM     [ProductCombinations]
              GROUP BY [ProductB]) a ON p.[ProductA] = b.[ProductB]
    GROUP BY [ProductA], [ProductB]
    ORDER BY ComboCount DESC
    

    【讨论】:

      【解决方案2】:

      子查询可以做到这一点。 (i 代表“内部”,o 代表“外部”)

      SELECT o.[ProductA], o.[ProductB], Count(*) as ComboCount, 
        (select count(*) from ProductCombinations.i where i.ProductA =   o.ProductA) as ACount,
        (select count(*) from ProductCombinations.i where i.ProductB = o.ProductB) as BCount
      FROM [ProductCombinations] o
      GROUP BY o.[ProductA], i.[ProductB]
      Order by o.ComboCount Desc
      

      【讨论】:

        【解决方案3】:

        我认为这很有效,而且很干净:

        SELECT DISTINCT [Product A], [Product B], 
            COUNT(*) OVER (PARTITION BY [Product A], [Product B]) ComboCount, 
            COUNT(*) OVER (PARTITION BY [Product A]) [Product A Count], 
            COUNT(*) OVER (PARTITION BY [Product B]) [Product B Count]
        FROM [ProductCombinations]
        ORDER BY ComboCount DESC
        

        【讨论】:

          猜你喜欢
          • 2014-11-23
          • 1970-01-01
          • 1970-01-01
          • 2022-06-10
          • 2019-06-09
          • 2019-12-01
          • 2018-09-20
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多