您声明我需要计算具有类似价格的商品。根据您的示例数据,您的查询可以工作。
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
列各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
和Profit
是不同的。因此,您需要删除SELECT
和GROUP BY
中的那些列以回答您的问题,我需要计算具有类似价格的项目。 另外还有,您可能还想从SELECT
和GROUP BY
中删除Store
列。
SELECT
Store,
Item,
Count(Price) as CT,
Price
FROM @table2
GROUP BY Store,Item,Price
您的查询是正确的,并且正在返回您的预期结果。它给你什么? – GurV
我得到3行,每行计数为1 – neualex
该查询是正确的。在你的varchar列中必须有一些隐藏的字符,因为我现在已经在我自己的系统上对它进行了测试并产生了正确的输出。 – GurV