SQL Join没有返回我期待的内容

时间:2009-01-20 22:32:35

标签: sql sql-server tsql

我有一个临时表我正在创建一个以下格式的查询。这包含了几年来每个CustomerID,Year和Month的记录。

#T

客户|客户ID |年|月

离。

Foo | 12345 | 2008 | 12  
Foo | 12345 | 2008 | 11  
Bar | 11224 | 2007 | 7

当我将这个临时表加入到以下格式的另一个表格中时,我得到的结果比我预期的要多得多。

事件

EventID |客户ID | DateOpened

离。

1100 | 12345 | '2008-12-11 10:15:43'
1100 | 12345 | '2008-12-11 11:25:17'

我正在尝试获取事件计数的结果集以及此类客户,年份和月份。

SELECT COUNT(EventID), Customer, Year, Month
FROM [Event] 
JOIN #T ON [Event].CustomerID = #T.CustomerID
WHERE [Event].DateOpened BETWEEN '2008-12-01' AND '2008-12-31'
GROUP BY Customer, Year, Month
ORDER BY Year, Month

我每年和每月都会获得一个记录,而不仅仅是2008年12月。

4 个答案:

答案 0 :(得分:2)

您要在事件表上指定日期,而不是在连接上指定日期 - 因此它将使用匹配的customerid连接临时表中的所有记录。

试试这个:

SELECT COUNT(e.EventID), T.Customer, T.Year, T.Month
FROM [Event] e
INNER JOIN #T T ON (
  T.CustomerID = e.CustomerID and 
  T.Year = year(e.DateOpened) and 
  T.Month = month(e.DateOpened) 
  ) 
WHERE T.Year = 2008 
  and T.Month = 12 
GROUP BY T.Customer, T.Year, T.Month
ORDER BY T.Year, T.Month

答案 1 :(得分:2)

也许你的意思是:

SELECT COUNT(EventID)
    ,Customer
    ,Year
    ,Month
FROM [Event] 
INNER JOIN #T
    ON [Event].CustomerID = #T.CustomerID
    AND YEAR([Event].DateOpened) = #T.YEAR
    AND MONTH([Event].DateOpened) = #T.MONTH
WHERE [Event].DateOpened >= '2008-12-01'
    AND [Event].DateOpened < '2009-01-01'
GROUP BY Customer
    ,Year
    ,Month
ORDER BY Year
    ,Month

注意,我已在您的代码中修复了另一个潜在错误:您的BETWEEN将排除'2008-12-31 10:15:43'之类的日期时间您可以使用此类似技术。

答案 2 :(得分:1)

问题是#T中有两行,CustomerID = 12345.这些行中的每一行都与Event中的每一行连接。如果您只想在12月份使用CustomerID,那么您还需要过滤#T

SELECT COUNT(EventID), Customer, Year, Month
    FROM [Event] 
    JOIN #T ON [Event].CustomerID = #T.CustomerID
    WHERE [Event].DateOpened BETWEEN '2008-12-01' AND '2008-12-31'
      AND #T.Year = 2008
      AND #T.Month = 12
    GROUP BY Customer, Year, Month
    ORDER BY Year, Month

如果您有其他期望,最好澄清一下您的问题。

答案 3 :(得分:0)

如果您只想要客户名称,那么#T会有多余的信息。

您可以使用子查询来解决它

SELECT COUNT(EventID), (select TOP 1 #T.Customer from #T Where #T.CustomerID = [Event].CustomerID ), Year, Month
FROM [Event] 
WHERE [Event].DateOpened BETWEEN '2008-12-01' AND '2008-12-31'
GROUP BY CustomerID, Year, Month
ORDER BY Year, Month