我有两个表拳头一个客户和第二个Orderdetails。我希望从病房第4位开始注册,并排除已购买的客户名单。
SELECT *
FROM Customer
WHERE RegisteredDate BETWEEN CONVERT(DATETIME,CONVERT(VARCHAR(50),'12/04/2015',101))
AND CONVERT(DATETIME,CONVERT(VARCHAR(50),'12/07/2015',101))
AND CustomerID NOT IN(SELECT *
FROM Customer c
INNER JOIN orderdetails od ON c.CustomerId = od.CustomerID
WHERE C.RegisteredDate
BETWEEN CONVERT(DATETIME,CONVERT(VARCHAR(50),'12/04/2015',101))
AND CONVERT(DATETIME,CONVERT(VARCHAR(50),'12/07/2015',101))
AND Transactionid IS NOT NULL
)
结果是:
Msg 116,Level 16,State 1,Line 13只有一个表达式 在未引入子查询时在选择列表中指定 存在。
答案 0 :(得分:2)
删除子查询中的*(所有列),并在子查询中指定select CustomerID而不是*(所有列)。
因为当使用 NOT IN 时,预期子查询返回的列数只有一个。
答案 1 :(得分:2)
正如其他答案中所提到的,IN运算符只需要在与子查询一起使用时返回一列,您应该只在子查询中选择cutomerID,但如果它有可能返回NULL值,那么使用EXISTS运算符就像....
SELECT *
FROM Customer c1
WHERE RegisteredDate BETWEEN CONVERT(DATETIME,'12/04/2015',101)
AND CONVERT(DATETIME,'12/07/2015',101)
AND NOT EXISTS (SELECT *
FROM Customer c
INNER JOIN orderdetails od ON c.CustomerId = od.CustomerID
WHERE C.RegisteredDate
BETWEEN CONVERT(DATETIME,'12/04/2015',101)
AND CONVERT(DATETIME,'12/07/2015',101)
AND Transactionid IS NOT NULL
AND C1.CustomerID = c.CustomerID
)
答案 2 :(得分:1)
您无法在子查询中使用select *
,您需要指定在这种情况下为customerid的列。
SELECT *
FROM Customer
WHERE RegisteredDate BETWEEN CONVERT(DATETIME,CONVERT(VARCHAR(50),'12/04/2015',101))
AND CONVERT(DATETIME,CONVERT(VARCHAR(50),'12/07/2015',101))
AND CustomerID NOT IN(SELECT c.CustomerID
FROM Customer c
INNER JOIN orderdetails od ON c.CustomerId = od.CustomerID
WHERE C.RegisteredDate
BETWEEN CONVERT(DATETIME,CONVERT(VARCHAR(50),'12/04/2015',101))
AND CONVERT(DATETIME,CONVERT(VARCHAR(50),'12/07/2015',101))
AND Transactionid IS NOT NULL
)