0

我想为这个问题写一个查询:

显示 1997 年 8 月没有下订单的日子。

我可以找到下订单的天数,但是如何找到没有下订单的天数?

这显示了下订单的日期:

SELECT
   o.OrderID,
   day(o.OrderDate) AS 'Date',
   sup.CompanyName 
FROM
   Orders o 
   INNER JOIN OrderDetails od ON o.OrderID = od.OrderID 
   INNER JOIN Products p ON od.ProductID = p.ProductID 
   INNER JOIN Suppliers sup ON p.SupplierID = sup.SupplierID 
WHERE
   sup.CompanyName = 'Tokyo Traders'
   AND o.OrderDate BETWEEN '1/1/1997' AND '1/31/1997'
4

3 回答 3

2

您需要一个可以加入的日期表来查找缺失的日期。

假设它的 SQL Server:

您可以加入您的查询以获取结果

WITH DatesTable
AS
(
  SELECT CAST('2007-08-01' as datetime) AS [date]
  UNION ALL
  SELECT DATEADD(dd, 1, [date])
  FROM DatesTable
  WHERE DATEADD(dd, 1, [date]) <= '2007-08-31'
)
SELECT [date] FROM DatesTable
OPTION (MAXRECURSION 0);

一些类似的东西

WITH DatesTable
AS
(
  SELECT CAST('2007-08-01' as datetime) AS [date]
  UNION ALL
  SELECT DATEADD(dd, 1, [date])
  FROM DatesTable
  WHERE DATEADD(dd, 1, [date]) <= '2007-08-31'
)
SELECT DT.[date]
FROM
   DatesTable DT 
   Left Outer Join Orders o on o.OrderDate = DT.[Date]

WHERE o.OrderDate is null

OPTION (MAXRECURSION 0);
于 2012-07-25T20:10:53.037 回答
0

执行此操作的跨数据库方法是创建一个包含每个日期的行的表,然后将其左连接到您的明细表;空值是没有匹配的地方。

于 2012-07-25T20:11:12.060 回答
0

假设 SQL Server:

WITH Dts AS (
   SELECT DateAdd(day, V.number, '19970801') Dt
   FROM master.dbo.spt_values V
   WHERE V.type = 'P'
   AND V BETWEEN 1 AND 31
)
SELECT Dts.Dt
WHERE NOT EXISTS (
   SELECT *
   FROM
      Orders o 
      INNER JOIN Suppliers sup ON p.SupplierID = sup.SupplierID 
   WHERE
      sup.CompanyName = 'Tokyo Traders'
      AND Dts.Dt = o.OrderDat
)

我在 CompanyName 上保留了您的情况,因为我认为您想要Tokyo Traders没有下订单的日子。

于 2012-07-25T20:15:26.363 回答