我不知道 orderdts 数据类型,但如果是日期时间,则不包括 2015-12-31 的订单(除非订单日期为 2015-12-31 00:00:00.000。请注意这将如何跳过第一条记录:
DECLARE @orders TABLE (CustomerID INT, orderDate DATETIME);
INSERT @orders VALUES (1, '2015-12-31 00:00:01.000'), (1, '2015-12-30'), (2, '2015-01-04');
SELECT * FROM @orders WHERE orderDate BETWEEN '2015-01-01' AND '2015-12-31';
在这种情况下,您可能希望 WHERE 子句过滤器看起来像:
WHERE orderDate BETWEEN '2015-01-01 00:00:00.000' AND '2015-12-31 23:59:59.999';
或者
WHERE CAST(orderDate AS date) BETWEEN '2015-01-01' AND '2015-12-31';
(第一个例子几乎肯定会表现得更好)。
现在,使用此示例数据:
-- Sample data
CREATE TABLE #LIST (LISTName varchar(10) NOT NULL);
INSERT #LIST
SELECT TOP (100) LEFT(newid(), 8)
FROM sys.all_columns a, sys.all_columns b;
-- You will probably want LISTName to be indexed
CREATE NONCLUSTERED INDEX nc_LISTName ON #LIST(LISTName);
您可以像这样实现 Paul 的解决方案:
DECLARE @LIST_Param varchar(8) = 'No List';
SELECT LISTName
FROM
(
SELECT distinct LISTName
FROM #LIST
UNION ALL
SELECT 'No List'
WHERE (SELECT COUNT(DISTINCT LISTName) FROM #LIST) < 1000000
) Distinct_LISTName
WHERE (@LIST_Param = 'No List' or @LIST_Param = LISTName);
或者,您可以这样做:
DECLARE @LIST_Param varchar(8) = 'No List';
WITH x AS
(
SELECT LISTName, c = COUNT(*)
FROM #LIST
WHERE (@LIST_Param = 'No List' or @LIST_Param = LISTName)
GROUP BY LISTName
),
c AS (SELECT s = SUM(c) FROM x)
SELECT LISTName
FROM x CROSS JOIN c
WHERE s < 1000000;