0

我的两张桌子是这样的

工作台

buyer   timeArrived               billed     paid

ABC     2013-02-08 10:30:00       60$        45$
CTS     2013-02-18 10:30:00       100$       80$
ABC     2012-03-11 10:30:00       60$        40$
MNT     2012-02-08 10:30:00       100$       60$
CTS     2012-03-11 10:30:00       60$        40$

购买者_t 表

buyer

ABC
MNT
CTS
GH

为了在他“最后一次见到”时搜索买家,我从买家表查询到购物表,例如

SELECT
 v.buyer,
 MAX(s.timeArrived) AS LastSeen
 FROM buyer_t AS b
 INNER JOIN shop as s ON b.buyer = s.buyer
 where 
 l.buyer = 'ABC' or l.buyer = 'CTS'
 GROUP BY b.buyer;

很高兴知道 ABC 和 CTS 何时购物,但我如何获得“计费”和“付费”列

4

1 回答 1

3

试试这个:

SELECT
 b.buyer,
 s.*
FROM buyer_t AS b
INNER JOIN shop as s ON b.buyer = s.buyer
INNER JOIN
(
   SELECT buyer, MAX(timeArrived) AS LastSeen
   FROM shop
   GROUP BY buyer
) AS s2  ON s.buyer = s2.buyer
        AND s.timeArrived = s2.lastSeen
WHERE s.buyer IN ('ABC', 'CTS');

SQL 小提琴演示

这会给你:

| BUYER |                     TIMEARRIVED | BILLED | PAID |
-----------------------------------------------------------
|   ABC | February, 08 2013 10:30:00+0000 |    60$ |  45$ |
|   CTS | February, 18 2013 10:30:00+0000 |   100$ |  80$ |

或者:既然您使用的是 SQL Server 2005,那么您可以使用排名功能 ROW_NUMBER() OVER(PARTITION BY ... ORDER BY ...)来做到这一点:

WITH CTE
AS
(
    SELECT
      s.*,
      ROW_NUMBER() OVER(PARTITION BY s.buyer
                        ORDER BY timeArrived DESC) AS Rownumber
    FROM buyer_t AS b
    INNER JOIN shop as s ON b.buyer = s.buyer
    WHERE s.buyer IN ('ABC', 'CTS')
) 
SELECT Buyer, TimeArrived, Billed, Paid
FROM CTE 
WHERE Rownumber = 1;

SQL Server 的 SQL Fiddle 演示

于 2013-03-19T11:23:57.393 回答