0

我想为第一个订单从 2015 年开始的客户选择所有记录。我也想要他们在 2015 年之后下的任何订单,但我不想要第一个订单是在 2016 年的客户的记录。我最终试图找到百分比订购两次以上的人,但我想排除 2016 年的新客户。

这不起作用,因为“mindate”是一个无效的列名,但我不确定为什么或如何尝试它。

Select 
    od.CustomerID, OrderID, OrderDSC, OrderDTS 
From 
    OrderDetail OD
Join 
    (Select 
         OrderID, Min(orderdts) as mindate
     From 
         OrderDetail
     Where  
         mindate Between '2015-1-1' and '2015-12-31'
     Group By Orderid) b on od.OrderID = b.OrderID 
4

4 回答 4

0

因为execution phases- 它是 seqency 如何评估 qry 和引擎。在 where 子句中,您的思维导图尚不存在。

您可以通过 orderdts 更改 mindate:

select OrderID, min(orderdts) as mindate
from OrderDetail
where orderdts between '2015-1-1' and '2015-12-31'
group by Orderid

第二种选择是使用having语句 - 它在group by.

于 2016-12-02T19:48:56.823 回答
0

尝试使用 EXISTS 子句。它基本上是一个子查询。下面是一个你应该能够适应的例子。

create table Test (Id int, aDate datetime)

insert Test values (1,'04/04/2014')
insert Test values (1,'05/05/2015')
insert Test values (1,'06/06/2016')
insert Test values (2,'04/30/2016')
insert Test values (3,'02/27/2014')


select t.* from Test t 
where
  aDate>='01/01/2015'
  and exists(select * from Test x where x.Id=t.Id and x.aDate >='01/01/2015' and x.aDate<'01/01/2016')
于 2016-12-02T20:02:05.553 回答
0

我要做的是选择位于您的日期范围之间的不同 CustomerID,并与表格进行左连接,以便过滤掉不属于您的日期范围之间的任何人。

SELECT * FROM 
    (Select DISTINCT(CustomerID) as CustomerID 
        FROM OrderDetail WHERE OrderDTS between '2015-1-1' AND '2015-12-31')  oIDs

LEFT JOIN

    OrderDetail OD

ON oIDs.CustomerID = OD.CustomerID
于 2016-12-02T19:53:38.340 回答
0

我不知道 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;
于 2016-12-02T22:51:19.070 回答