如何从每个结果中提取ID,Stype和第一个Statustime

时间:2017-09-08 22:28:27

标签: sql sql-server

我有来自3个表和我编写的查询的以下查询结果。 enter image description here 所以我想得到:

1st 67807 order and  2017-04-07 16:28:04.100
2nd I wanted 19859 Quote 2017-02-27 10:04:55.240

从所有结果来看,如何编写查询,带来结果的查询是:

SELECT * 
FROM   (SELECT qstatus AS Status, 
               quoteid AS ID, 
               'Quote' AS stype, 
               statusdescription, 
               statustime 
        FROM   quotestatus 
        WHERE  quoteid IN (SELECT quoteid 
                           FROM   quotes 
                           WHERE  customerid = 1 
                                  AND isseen = 0) 
        UNION ALL 
        SELECT ostatus AS Status, 
               orderid AS ID, 
               'Order' AS stype, 
               statusdescription, 
               statustime 
        FROM   orderstatus 
        WHERE  orderid IN(SELECT orderid 
                          FROM   orders 
                          WHERE  customerid = 1 
                                 AND isseen = 0) 
        UNION ALL 
        SELECT istatus   AS Status, 
               invoiceid AS ID, 
               'Invoice' AS stype, 
               statusdescription, 
               statustime 
        FROM   invoicestatus 
        WHERE  invoiceid IN (SELECT invoiceid 
                             FROM   invoices 
                             WHERE  customerid = 1 
                                    AND isseen = 0)) AS unionall 
ORDER  BY statustime DESC 

I have Quote, Invoice and Order table and when any change happens I wanted to notify them. 

1 个答案:

答案 0 :(得分:0)

您可以尝试以下操作,创建分区并选择第一行的所有分区。

 SELECT
      *
    FROM (SELECT
      ID,
      stype,
      statustime,
      ROW_NUMBER() OVER (PARTITION BY ID, stype ORDER BY statustime DESC) AS rownum
    FROM (SELECT
      qStatus AS Status,
      quoteID AS ID,
      'Quote' AS stype,
      statusDescription,
      statustime
    FROM QuoteStatus
    WHERE quoteID IN (SELECT
      quoteID
    FROM Quotes
    WHERE customerID = 1
    AND IsSeen = 0)
    UNION ALL
    SELECT
      oStatus AS Status,
      orderID AS ID,
      'Order' AS stype,
      statusDescription,
      statustime
    FROM OrderStatus
    WHERE orderID IN (SELECT
      orderID
    FROM Orders
    WHERE customerID = 1
    AND IsSeen = 0)
    UNION ALL
    SELECT
      iStatus AS Status,
      invoiceID AS ID,
      'Invoice' AS stype,
      statusDescription,
      statustime
    FROM InvoiceStatus
    WHERE invoiceID IN (SELECT
      invoiceId
    FROM Invoices
    WHERE customerID = 1
    AND IsSeen = 0)) AS unionall) AS ty
    WHERE rownum = 1
    ORDER BY statustime DESC;