SQL Server 2000中两组数据的差异
我正在尝试计算过去 3 个月内计费的客户与整个客户群之间的差异。我已经能够使用以下 SQL 来计算已计费的客户。
DECLARE @DateFrom AS DATETIME
SET @DateFrom =
CONVERT(DATETIME, CAST(YEAR(GETDATE()) AS VARCHAR(4)) +
'-' +
CAST(MONTH(DATEADD(MONTH, -3, GETDATE())) AS VARCHAR(2)) + '-01', 120)
DECLARE @DateTo AS DATETIME
SET @DateTo =
CONVERT(DATETIME, CAST(YEAR(GETDATE()) AS VARCHAR(4)) +
'-' +
CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-01', 120)
SELECT DISTINCT
i.CustomerCode
FROM
Invoice AS i
WHERE
(i.InvoiceDate > @DateFrom AND i.InvoiceDate < @DateTo)
我将要比较的表是 Customer 表,它也有一个 CustomerCode 字段。
提前致谢!
编辑
花了很长时间试图解决这个问题,并在此处发布此消息几分钟后,我找到了解决方案。使用 NOT IN 子句!
SELECT
c.CustomerCode
FROM
[Customer] AS c
WHERE
c.CustomerCode NOT IN (
SELECT DISTINCT
i.CustomerCode
FROM
[Invoice] AS i
WHERE
(i.InvoiceDate >= @DateFrom AND i.InvoiceDate < @DateTo))
在我的情况下,当我在 Management Studio 中测试每个步骤时,这似乎比下面提到的步骤执行得更快。
I am trying to work out the difference between customers that have been billed in the last 3 months and the whole customer base. I have been able to calculate the customers that have been billed using the following SQL
DECLARE @DateFrom AS DATETIME
SET @DateFrom =
CONVERT(DATETIME, CAST(YEAR(GETDATE()) AS VARCHAR(4)) +
'-' +
CAST(MONTH(DATEADD(MONTH, -3, GETDATE())) AS VARCHAR(2)) + '-01', 120)
DECLARE @DateTo AS DATETIME
SET @DateTo =
CONVERT(DATETIME, CAST(YEAR(GETDATE()) AS VARCHAR(4)) +
'-' +
CAST(MONTH(GETDATE()) AS VARCHAR(2)) + '-01', 120)
SELECT DISTINCT
i.CustomerCode
FROM
Invoice AS i
WHERE
(i.InvoiceDate > @DateFrom AND i.InvoiceDate < @DateTo)
The table that I will be comparing against will be the Customer table which also has a CustomerCode field.
Thanks in advance!
EDIT
After spending ages trying to figure this out and just after a few minutes of posting this message here I found a solution. Using the NOT IN clause!
SELECT
c.CustomerCode
FROM
[Customer] AS c
WHERE
c.CustomerCode NOT IN (
SELECT DISTINCT
i.CustomerCode
FROM
[Invoice] AS i
WHERE
(i.InvoiceDate >= @DateFrom AND i.InvoiceDate < @DateTo))
In my senario this appears to perform quicker then the steps mentioned below when I tested each in Management Studio.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过以下方式改进日期处理:
注意我在开始时使用了 >=,您在开始日期上缺少时间为 00:00:00 的行。
要获取过去 3 个完整月内没有发票的所有客户,您也可以这样写:
you can improve your date handling with:
notice I used >= on the start, you are missing rows on the start date with a time of 00:00:00.
to get all the customers that did not have invoices within the last 3 full months, you could also write it this way:
为了获得在一段时间内没有被计费的客户:
尽管我会用 KM 的建议替换
@DateFrom 和 @DateTo
日期范围检查,以避免使用变量。To get the customers that have not being billed during some period of time:
Though I would replace the
@DateFrom and @DateTo
date range checks with suggestion of KM to avoid using variables.