我有表pricedata
(参见附件)。我想在此表中添加两个额外的列(MinPrice of Competitor
和CompetitorID of MinPrice
)。我写了一个代码来获取列MinPrice of Competitor
,但我不知道如何获得第二列,任何帮助????
代码:
select a.ValuationDate, a.shop, a.Itemcode, a.OwnPrice,
a.[sales price competitor], a.[competitor ID], b.MinPrice
from [PriceTable] a
inner join
(select ValuationDate, Shop, ItemCode,
min([sales price competitor]) as MinPrice
FROM [PriceTable]
group by ValuationDate, Shop, ItemCode) b
on a.ValuationDate = b.ValuationDate
and a.Shop = b.Shop
and a.ItemCode = b.ItemCode
实际表格:
必填表:
答案 0 :(得分:1)
你走了。希望这会有所帮助。
select
a.ValuationDate,
a.shop
a.Itemcode,
a.OwnPrice,
a.[sales price competitor],
a.[competitor ID],
b.MinPrice ,
MINCOMPID.[competitor ID] AS 'CompetitorID of MinPrice'
from [PriceTable] a
inner join
(
select ValuationDate, Shop, ItemCode, min([sales price competitor]) as MinPrice FROM [PriceTable]
group by ValuationDate, Shop, ItemCode
) b
on a.ValuationDate=b.ValuationDate and a.Shop=b.Shop and a.ItemCode=b.ItemCode
INNER JOIN [PriceTable] AS MINCOMPID
ON MINCOMPID.ValuationDate=b.ValuationDate and MINCOMPID.Shop=b.Shop and MINCOMPID.ItemCode=b.ItemCode AND MINCOMPID.[sales price competitor]=b.MinPrice
答案 1 :(得分:1)
看(未经测试)。获取具有最小/最大值的行的常用方法是SELECT TOP(1).. ORDER BY .. DESC / ASC
select a.ValuationDate, a.shop, a.Itemcode, a.OwnPrice,
a.[sales price competitor], a.[competitor ID],
c.MinPrice, c.[competitor ID]
from [PriceTable] a
cross apply
(SELECT TOP(1) b.[competitor ID]
b.[sales price competitor] as MinPrice
FROM [PriceTable] b
WHERE a.ValuationDate = b.ValuationDate
and a.Shop = b.Shop
and a.ItemCode = b.ItemCode
ORDER BY b.[sales price competitor] DESC) c