0

我有 2 张桌子,CustomerMaster, EntBookings,现在对于每个客户,我在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

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

4

1 回答 1

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
于 2013-01-25T07:26:27.183 回答