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

Sql server SQL如何计算具有相似值的多个列,sql-server,count,multiple-columns,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 Price Cost Profit ------- ------ ------- ------ -------- ABC Beer 5 3 2 ABC Beer 5 3 2 ABC Beer 4 3 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
但是如果每个
商店/商品/计数的
成本
利润
元组不同,则分组不会显示所需的结果

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
假设在您的实际数据中,情况就是这样——即您的
成本
利润
是不同的。因此,您需要从
SELECT
groupby
中删除这些列。为了回答您的问题,我需要计算价格相似的商品另外,您可能需要从
选择
分组依据
中删除
存储

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

您的查询是正确的,正在返回预期结果。它给了你什么?我得到3行,每行的计数为1。查询是正确的。您的varchar列中一定有一些隐藏字符,因为我刚刚在自己的系统上对其进行了测试,并生成了正确的输出。您不是真的在尝试获取列值相似的行的“计数”吗?这些数字中是否有按浮点数分组的?如果是,您需要将它们转换为具有适当精度和比例的小数,以使其正常工作。价格可能会发生变化,通常是降价或原价,成本永远不会发生变化。我想我必须使用两个表格才能得到我需要的结果。第一个表,store/item/count/price,第二个表包括成本/利润。@neualex按照您的建议规范化您的数据通常是一个很好的主意。如果我在表中只有一个存储,例如ABC,那么对该存储的类似价格的计算是正确的,但是如果我至少有3个不同的存储(S1、S2、S3),并且它们都有类似的价格,如何计算每家商店的类似价格?相同的查询统计所有门店的相似价格,而不是每个门店。如果需要,我可以提供数据。最后一次查询是按每个存储区进行的。从select和group by中删除存储将获得总体结果。如果这不起作用,我会提出一个新问题,并提供示例数据和预期输出,以便每个人都能提供帮助
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
SELECT 
    Store,
    Item,
    Count(Price) as CT,
    Price
FROM @table2
GROUP BY Store,Item,Price