SQL按过滤器计算项目外的项目

时间:2015-04-27 17:16:20

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

假设我有下表:

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

3 个答案:

答案 0 :(得分:1)

您可以单独统计每个产品,并将其与当前查询相结合:

var distance= 0;
for(i = 0; i < response.routes[0].legs.length; i++){
   distance += parseFloat(response.routes[0].legs[i].distance.value);
       //for each 'leg'(route between two waypoints) we get the distance and add it to the total
}   
console.log(distance);

答案 1 :(得分:1)

这很好用,我觉得很干净:

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

答案 2 :(得分:0)

子查询可以做到这一点。 (我是“内在的”,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