2014-10-17 56 views
0

,如果我有以下數據表SQL獲得最高的價值和串聯

ProductID,StockOnSite,StockOffsite 
    1   83   81  
    1   98   85  
    1   112   101  
    2   81   85  
    2   115   83  
    2   115   101  

我需要做的就是讓每個產品ID的最高StockOnSite(計算StockDifference)記錄和concatinate StockOnSite與StockOffsite創建列StockInfo

輸出需要

ProductID,StockOnSite,StockOffsite,StockDifference,StockInfo 
    1   98   85   13   98/85 
    2   115   83   32   115/83 

SQL我已經想出

select ProductID 
     ,StockOnSite 
     ,StockOffsite 
     ,StockDifference = max(StockOnSite - StockOffsite) 
from Product 
group by ProductID, StockOnSite, StockOffsite 

我不知道該從哪裏出發?

感謝

下面是查詢建表和數據:

CREATE TABLE Products 
(
    ProductID int NOT NULL, 
    StockOnSite int NOT NULL, 
    StockOffsite int NOT NULL 
) 

insert into table Products(ProductID, StockOnSite, StockOffsite) values(1,83,81) 
insert into table Products(ProductID, StockOnSite, StockOffsite) values(1,98,85) 
insert into table Products(ProductID, StockOnSite, StockOffsite) values(1,112,101) 
insert into table Products(ProductID, StockOnSite, StockOffsite) values(2,81,85) 
insert into table Products(ProductID, StockOnSite, StockOffsite) values(2,115,83) 
insert into table Products(ProductID, StockOnSite, StockOffsite) values(2,115,101) 
+0

你爲什麼選98爲產品1,當有也115?是因爲你在尋找最大的差異嗎? – dasblinkenlight 2014-10-17 09:04:02

+0

你正在使用哪些DBMS? Postgres的?甲骨文? – 2014-10-17 09:12:42

+0

ProductID 1的差異是98-85 = 13 – user142617 2014-10-17 09:14:36

回答

1
select ProductID 
     ,StockOnSite 
     ,StockOffsite 
     ,StockOnSite - StockOffsite 
     ,cast(Stockonsite as varchar(10))+'/' +cast(StockOffsite as varchar(10)) 
from Products pr1 
where StockOnSite - StockOffsite = (Select max(StockOnSite - StockOffsite) 
             from Products pr2 
             where pr1.ProductID = pr2.ProductID 
             ) 
group by ProductID, StockOnSite, StockOffsite 
1

這應該做的伎倆。
查詢需要跟蹤產品中,以便在發生在超過1種產品的同一股票的區別並不感到困惑:

select p.ProductID 
     ,p.StockOnSite 
     ,p.StockOffsite 
     ,(p.StockOnSite - p.StockOffsite) StockDifference 
     ,concat(p.StockOnSite,'/',p.StockOffsite) StockInfo 
from Products p 
where concat(ProductID,'-',(StockOnSite - StockOffsite)) = 
     (
     select concat(ProductID,'-',max((StockOnSite - StockOffsite))) 
     from Products p2 
     where p2.ProductID = p.ProductID 
     group by ProductID 
     ) 
;