我的数据库有两张桌子,一张车桌和一张轮桌 我试图在几天内找到满足特定条件的车轮数量,但输出中不包含某些天数。
以下是查询:
USE CarDB
SELECT MONTH(c.DateTime1) 'Month',
DAY(c.DateTime1) 'Day',
COUNT(w.ID) 'Wheels'
FROM tblCar c
INNER JOIN tblWheel w
ON c.ID = w.CarID
WHERE c.DateTime1 BETWEEN '05/01/2013' AND '06/04/2013'
AND w.Measurement < 18
GROUP BY MONTH(c.DateTime1), DAY(c.DateTime1)
ORDER BY [ Month ], [ Day ]
GO
输出结果似乎是正确的,但是没有显示0轮的天数。例如:
采样电流输出:
Month Day Wheels
2 1 7
2 2 4
2 3 2 -- 2/4 is missing
2 5 9
所需的输出样本:
Month Day Wheels
2 1 7
2 2 4
2 3 2
2 4 0
2 5 9
我也试过左连接,但似乎没有用。
答案 0 :(得分:1)
您可能想要使用LEFT OUTER JOIN
:
USE CarDB
SELECT MONTH (c.DateTime1) 'Month', DAY (c.DateTime1) 'Day', COUNT (w.ID) 'Wheels'
FROM tblCar c LEFT OUTER JOIN tblWheel w ON c.ID = w.CarID
WHERE c.DateTime1 BETWEEN '05/01/2013' AND '06/04/2013'
AND (w.Measurement IS NULL OR w.Measurement < 18)
GROUP BY MONTH (c.DateTime1), DAY (c.DateTime1)
ORDER BY [Month], [Day]
GO
然后,您需要调整WHERE条件,因为您希望由于OUTER连接而使w.Measurement
的行保持为NULL
。
答案 1 :(得分:1)
您使用LEFT JOIN
尝试使用此类外部联接运行查询,但删除WHERE
子句。注意什么?
发生了什么是应用了连接,然后where子句删除了不符合条件的值。所有这一切都发生在小组之前,意味着汽车被排除在外。
以下是您的一种方法:
SELECT Year(cars.datetime1) As the_year
, Month(cars.datetime1) As the_month
, Day(cars.datetime1) As the_day
, Count(wheels.id) As wheels
FROM (
SELECT id
, datetime1
FROM tblcar
WHERE datetime1 BETWEEN '2013-01-05' AND '2013-04-06'
) As cars
LEFT
JOIN tblwheels As wheels
ON wheels.carid = cars.id
这一次的不同之处在于,我们在加入轮桌之前限制了购物车的结果。
答案 2 :(得分:0)
删除联接并将您的选择更改为:
SELECT MONTH (c.DateTime1) 'Month', DAY (c.DateTime1) 'Day', isnull(select top 1 (select COUNT from tblWheel where id = tblCar.ID and Measurement < 18), 0) 'Wheels'