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

时间:2017-01-10 18:57:56

标签: sql-server count multiple-columns

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

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

我需要计算价格相似的商品,因此上表的结果应该类似于......

  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

思想?

1 个答案:

答案 0 :(得分:1)

您声明我需要计算价格相似的商品。根据您的示例数据,您的查询可以正常运行。

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

,如果每个Cost Profit的{​​{1}}和Store / Item / Count列不同,则您的分组不会显示你想要的结果。

tuple

假设在您的真实数据中,情况就是这样 - 即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 Cost不同。因此,您需要从ProfitSELECT中删除这些列才能回答您的问题,我需要计算价格相似的商品 Additionaly ,您可能还希望从GROUP BYStore中移除SELECT列。

GROUP BY