2014-11-04 20 views
0

我有一個採購訂單表像這樣檢索下一個採購訂單到期價格:從訂單

+---------------+------------+---------+----------+-------+ 
| PurchaseOrder | DueDate | Product | Quantity | Price | 
+---------------+------------+---------+----------+-------+ 
| PO1   | 04/12/2014 | A  |  20 | 19 | 
| PO2   | 20/11/2014 | B  |  16 | 22 | 
| PO3   | 07/11/2014 | A  |  14 | 32 | 
| PO4   | 09/12/2014 | B  |  7 | 86 | 
+---------------+------------+---------+----------+-------+ 

我想查詢來總結數量爲每個產品,顯示下一個到期日,和顯示即將到期的該採購訂單的價格。

所需的輸出將是:

+---------+---------------+--------------+------------------+ 
| Product | TotalQuantity | NextDueDate | NextDueDatePrice | 
+---------+---------------+--------------+------------------+ 
| A  |   34 | 07/11/2014 |    32 | 
| B  |   23 | 20/11/2014 |    22 | 
+---------+---------------+--------------+------------------+ 

我不知道該怎麼做(以最有效的方式),該位將得到NextDueDatePrice!

我設置它做所有但列,如果有幫助的SQLFiddle:http://sqlfiddle.com/#!3/942ed/2

非常感謝提前收到任何幫助!

+0

你將需要一個子查詢它獲取最大的'DurDate'當前產品。 – Richard 2014-11-04 11:47:04

回答

0

使用子查詢方法:

SQL Fiddle

MS SQL Server 2008的架構設置

CREATE TABLE PurchaseOrders 
(
    PurchaseOrder varchar(255), 
    DueDate datetime, 
    Product varchar(255), 
    Quantity int, 
    Price int, 
); 
INSERT INTO PurchaseOrders VALUES ('PO1','2014-12-04','A',20,19); 
INSERT INTO PurchaseOrders VALUES ('PO2','2014-11-20','B',16,22); 
INSERT INTO PurchaseOrders VALUES ('PO3','2014-11-07','A',14,32); 
INSERT INTO PurchaseOrders VALUES ('PO4','2014-12-09','B',7,86); 

查詢1

SELECT 
    Product, 
    SUM(Quantity) AS TotalQuantity, 
    MIN(DueDate) AS NextDue, 
    (select Price 
    from PurchaseOrders p2 
    where p2.Product = p1.Product and p2.DueDate = MIN(p1.DueDate)) as NextPrice 
FROM PurchaseOrders p1 
GROUP BY Product 

Results

| PRODUCT | TOTALQUANTITY |       NEXTDUE | NEXTPRICE | 
|---------|---------------|---------------------------------|-----------| 
|  A |   34 | November, 07 2014 00:00:00+0000 |  32 | 
|  B |   23 | November, 20 2014 00:00:00+0000 |  22 | 
1

TotalQuantity你可以使用基本聚集功能,但不能因此NextDueDatePrice。相反,訣竅是使用row_number()枚舉行,然後使用條件彙總:

select Product, sum(Quantity) as TotalQuantity, Max(DueDate) as NextDueDate, 
     max(case when seqnum = 1 then Price end) as NextDueDatePrice 
from (select po.*, row_number() over (partition by Product order by DueDate) as seqnum 
     from PurchaseOrders po 
    ) po 
group by Product;