如果找不到特定日期的记录,我正在尝试使此查询在“nb”字段中显示0。现在输出为0行,除非我指定的日期存在于“Commande”表中。
SELECT
isnull(COUNT(*), 0) as nb,
CONVERT(date, c.Date_commande) as Date_commande,
f.Code_fournis
FROM Commande c
LEFT JOIN Fournisseur f
ON c.Code_fournis = f.Code_fournis
WHERE f.Code_fournis = 'XNZ'
AND Convert(date, c.Date_commande) = '2015-10-28'
GROUP BY CONVERT(date, c.Date_commande), f.Code_fournis
ORDER BY c.date_commande desc
答案 0 :(得分:0)
The problem is you can't count what isn't there. You need create a table allDates
for all the dates. 100 years mean 36,500 rows so is a small table. Use this one as example
How can I generate a temporary table filled with dates in SQL Server 2000?
Then
SELECT
isnull(COUNT(*), 0) as nb,
CONVERT(date, AD.date) as Date_commande,
f.Code_fournis
FROM
allDates AD
LEFT JOIN Commande c
ON AD.date = CONVERT(date, c.Date_commande)
LEFT JOIN Fournisseur f
ON c.Code_fournis = f.Code_fournis
WHERE f.Code_fournis = 'XNZ'
AND Convert(date, c.Date_commande) = '2015-10-28'
GROUP BY CONVERT(date, AD.date), f.Code_fournis
ORDER BY AD.date desc
答案 1 :(得分:-1)
因为Commande中不存在'2015-10-28',您需要在虚拟表中为它创建一行:
SELECT
SUM(case when c.Date_commande is null then 0 else 1 end) as nb,
d.Date_commande as Date_commande,
f.Code_fournis
FROM (values(cast('20150101' as date), 'XNZ') as d(Date_commande, Code_fournis)
LEFT JOIN Commande c on Cast(c.Date_commande as date) = d.Date_commande
LEFT JOIN Fournisseur f
ON c.Code_fournis = f.Code_fournis and f.Code_fournis = d.Code_fournis
GROUP BY d.Date_commande, f.Code_fournis
ORDER BY d.Date_commande desc
这也可行:
SELECT isnull(COUNT(*), 0) as nb,
CONVERT(date, c.Date_commande) as Date_commande,
f.Code_fournis
From your query
Union All
Select 0, '20150101', 'XNZ'
Where not exist (
select 1
From Commande c
LEFT JOIN Fournisseur f
ON c.Code_fournis = f.Code_fournis and = d.Code_fournis
Where f.Code_fournis = 'XNZ'
AND Convert(date, c.Date_commande) = '20150101'
)
答案 2 :(得分:-1)
即使这是旧的并且有一些downvotes,我最近解决了我的问题。我不得不生成一个包含日期的表格。
SELECT SUM(CONVERT(int, case(vtl.oeil) WHEN RTRIM('I') THEN 2 ELSE 1 END)) as nb,
CONVERT(date, c.Date_commande) as Date_commande,
RTRIM(f.Code_fournis) AS Code_fournis
FROM Commande c
LEFT JOIN Fournisseur f
ON c.Code_fournis = f.Code_fournis
WHERE c.Code_fournis = 'XNZ'
AND Convert(date, c.Date_commande)
BETWEEN '2015-11-30'
AND '2015-12-04'
GROUP BY CONVERT(date, c.Date_commande), f.Code_fournis
UNION ALL
SELECT '0', date, 'XNZ'
FROM allDates
WHERE date
BETWEEN '2015-11-30'
AND '2015-12-04'
AND date NOT IN (
SELECT convert(date, c.Date_commande) as date
FROM allDates ad
INNER JOIN Commande c
ON ad.date = convert(date, c.Date_commande)
WHERE c.Code_fournis = 'XNZ'
and convert(date, c.Date_commande)
BETWEEN '2015-11-30'
AND '2015-12-04'
)
ORDER BY c.date_commande asc
它与我要求的有点不同,但希望它可以帮助某人。