sql查询列出没有groupby / aggregate的列

时间:2013-03-19 11:20:49

标签: c# sql sql-server tsql

我的两张桌子看起来像这样

购物台

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$

buyer_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何时购物 但我如何获得“收费”和“付费”栏目

1 个答案:

答案 0 :(得分: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 Fiddle Demo

这会给你:

| 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,因此您可以使用ranking function 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 Fiddle Demo for SQL Server