每个客户选择最小预订日期

时间:2013-01-25 07:22:28

标签: sql sql-server tsql

我有2个表,CustomerMasterEntBookings,现在每个客户,我都在EntBookings表中记录了他们的每个预订。 我想要的是,找出所有客户的第一个预订日期。

我尝试了什么,

SELECT cm.CustomerCode,
       cm.CustomerName,
       MIN(eb.BookingDate) OVER(PARTITION BY eb.BookingByCustomer)
FROM   EntBookings eb
       INNER JOIN CustomerMaster cm
            ON  cm.CustomerCode = eb.BookingByCustomer
GROUP BY
       cm.CustomerCode,
       cm.CustomerName,
       eb.BookingByCustomer,
       eb.BookingDate 

它将结果显示为

Cust1   ABC     2013-01-24 00:00:00.000
Cust2   ABCD    2013-01-24 00:00:00.000
Cust2   ABCD    2013-01-24 00:00:00.000
Cust3   BCD     2013-01-25 00:00:00.000
Cust4   BCDE    2013-01-24 00:00:00.000
Cust7   DEF     2013-01-02 00:00:00.000

我不知道Cust2为什么显示2行?我怎样才能让它返回一行?

如果我这样做..

SELECT cm.CustomerCode,
       cm.CustomerName,
       MIN(eb.BookingDate) OVER(PARTITION BY eb.BookingDate)
FROM   EntBookings eb
       INNER JOIN CustomerMaster cm
            ON  cm.CustomerCode = eb.BookingByCustomer
GROUP BY
       cm.CustomerCode,
       cm.CustomerName,
       eb.BookingByCustomer,
       eb.BookingDate 

我明白了......

Cust7   DEF     2013-01-02 00:00:00.000
Cust1   ABC     2013-01-24 00:00:00.000
Cust2   ABCD    2013-01-24 00:00:00.000
Cust4   BCDE    2013-01-24 00:00:00.000
Cust3   BCD     2013-01-25 00:00:00.000
Cust2   ABCD    2013-02-13 00:00:00.000

在这种情况下,虽然我仍然为Cust2获取了2行,但日期是错误的,它应该是2013-01-24 00:00:00.000(如第一种情况),但是返回2行。因此,这两个查询都是不正确的。谁能帮我弄清楚我做错了什么?

1 个答案:

答案 0 :(得分:2)

你使事情变得复杂,而你的分组太多了。您似乎只想对客户代码和名称进行分组。

SELECT 
     cm.CustomerCode, 
     cm.CustomerName, 
     MIN(eb.BookingDate) 
 FROM 
      EntBookings eb
 JOIN
      CustomerMaster cm     ON       
       cm.CustomerCode = eb.BookingByCustomer
 GROUP BY
       cm.CustomerCode, cm.CustomerName