SQL 如何计算具有相似值的多个列

SQL How to count multiple columns with similar values

我有一个 table 有几家商店的商品销售,请参阅下面的示例 table。

  Store   Item   Price   Cost   Profit  
 ------- ------ ------- ------ -------- 
  ABC     Beer       5      3        2  
  ABC     Beer       5      3        2  
  ABC     Beer       4      3        1  

我需要计算价格相似的商品,所以上面 table 的结果应该类似于...

  Store   Item   Count   Price   Cost   Profit  
 ------- ------ ------- ------- ------ -------- 
  ABC     Beer       2       5      3        2  
  ABC     Beer       1       4      3        1  

我尝试了 SQL 查询但没有成功...

SELECT Store,Item,Count(Price),Price,Cost,Profit
FROM Table
GROUP BY Store,Item,Price,Cost,Profit

想法?

您声明我需要清点价格相似的商品。根据您的示例数据,您的查询有效。

declare @table table (Store varchar(3), Item varchar(16), Price int, Cost int, Profit int)
insert into @table (Store, Item, Price, Cost, Profit) 
values

('ABC','Beer',5,3,2),
('ABC','Beer',5,3,2),  
('ABC','Beer',4,3,1)  

SELECT 
    Store,
    Item,
    Count(Price) as CT,
    Price,
    Cost,
    Profit
FROM @table
GROUP BY Store,Item,Price,Cost,Profit

但是,如果每个 Store / Item / Count tupleCostProfit 列不同,您的分组就不会没有显示你想要的结果。

declare @table2 table (Store varchar(3), Item varchar(16), Price int, Cost int, Profit int)
insert into @table2 (Store, Item, Price, Cost, Profit) 
values

('ABC','Beer',5,3,2), --notice change in cost and profit
('ABC','Beer',5,2,1), --notice change in cost and profit 
('ABC','Beer',4,3,1)  

SELECT 
    Store,
    Item,
    Count(Price) as CT,
    Price,
    Cost,
    Profit
FROM @table2
GROUP BY Store,Item,Price,Cost,Profit

假设在你的真实数据中,是这样的——也就是说你的CostProfit是不一样的。因此,您需要从 SELECTGROUP BY 中删除这些列才能回答您的问题,我需要计算具有相似价格的商品另外,您可能还想从 SELECTGROUP BY 中删除 Store 列。

SELECT 
    Store,
    Item,
    Count(Price) as CT,
    Price
FROM @table2
GROUP BY Store,Item,Price