SQL Server查询 - 查找最后的订单数据

时间:2018-02-22 17:23:57

标签: sql sql-server

我有历史记录(没有正在进行的月份数据)表T1:

picture 1

* na - 客户取消的服务

当前(201706)表T2(有持续月份的数据):

picture 2

如何编写Microsoft SQL Server查询以查找客户aaaa当前服务的最新订单日期?

答案:aaaa在201706订购了2,在201705订购了bbb - 1.

2 个答案:

答案 0 :(得分:0)

SELECT customer,service from T1 
GROUP BY customer,service HAVING service >=1 
ORDER BY ordered DESC

答案 1 :(得分:0)

我建议每位客户只检索一个日期:

SELECT
latest_date.Customer as Customer,
T1.Service as Service
FROM
    (SELECT 
        Customer as Customer,
        max(Ordered) as date
    FROM T1 GROUP BY Customer) latest_date
    LEFT JOIN T1
        ON  latest_date.date=T1.ordered
GROUP BY Customer,Service