2016-05-25 6 views
1

テーブルpricedata(添付ファイル参照)があります。私はこのテーブル(MinPrice of CompetitorCompetitorID of MinPrice)に2つの余分な列を追加したいと思います。私は、列MinPrice of Competitorを取得するコードを書いたが、私はどのように2番目の列、任意の助けを得るために考えていないか?新しい列のテーブル内の選択

コード:

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 

実際のテーブル:

Actual Table

必要なテーブル:ここに行く

Required Table

+0

は誰別の人のように良いquestion.Thinkあなたの自己を依頼する方法についてはこちらをご覧くださいあなたが何を求めているのか、最大限の助けを得るために何ができるのかについての手掛かりはありません:https://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public -forum/ – TheGameiswar

+0

サンプルデータを減らし、期待される結果も表示してください! – jarlh

答えて

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

見てください(テストされていません)。最小/最大値はSELECT TOPであるとの行を取得する一般的な方法は、(1).. DESC/ASC BY ORDER

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 
関連する問題