我的查询可以获得具有销售标题或在日期之间具有销售发票的客户' 2014-06-01' AND' 2014-12-31'。
现在,我想创建一个两个新列,显示日期' 2014-06-01'之间的销售发票数量。 AND' 2014-12-31'和每个客户得到的销售标题。
这里的问题是我真的不懂得思考,我得到了这个错误
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
这是我的SQL查询。
SELECT t1.Name, /*THIS PART GIVES ME THE ERROR*/ (SELECT COUNT(t5.[Bill-to Customer No_]) as he
FROM [dbo].[MNO International AB$Sales Header] t5
WHERE EXISTS
(SELECT * FROM [dbo].[MNO International AB$Customer] t6
WHERE t5.[Bill-to Customer No_]=t6.[No_])
GROUP BY t5.[Bill-to Name]
) as TempSa
FROM [dbo].[MNO International AB$Customer] t1
WHERE (EXISTS
(SELECT *
FROM [dbo].[MNO International AB$Sales Header] t2
WHERE t2.[Bill-to Customer No_] =t1.[No_])
OR EXISTS
(SELECT *
FROM [dbo].[MNO International AB$Sales Invoice Header] t3
WHERE t3.[Posting Date] BETWEEN '2014-06-01' AND '2014-12-31' AND t3.[Bill-to Customer No_] = t1.No_))
这两个查询在每个客户的日期之间为每个客户和发票提供了适当数量的销售标题。如何将这两个查询合并到上面查询中的select语句?
SELECT t1.[Bill-to Name], COUNT(t1.[Bill-to Customer No_]) as Temp
FROM [dbo].[MNO International AB$Sales Header] t1
WHERE EXISTS
(SELECT * FROM [dbo].[MNO International AB$Customer] t2
WHERE t1.[Bill-to Customer No_]=t2.[No_] )
GROUP BY t1.[Bill-to Name]
SELECT t1.[Bill-to Name], COUNT(t1.[Bill-to Customer No_]) as Temp
FROM [dbo].[MNO International AB$Sales Invoice Header] t1
WHERE EXISTS
(SELECT * FROM [dbo].[MNO International AB$Customer] t2
WHERE t1.[Bill-to Customer No_]=t2.[No_] AND t1.[Posting Date] BETWEEN '2014-06-01' AND '2014-12-31' AND t2.[No_]='101716' )
GROUP BY t1.[Bill-to Name]
答案 0 :(得分:1)
子查询中有GROUP BY
。我不确定您是否只需要删除它或用相关子句替换它,但这将修复语法错误:
SELECT t1.Name,
(SELECT COUNT(t5.[Bill-to Customer No_]) as he
FROM [dbo].[MNO International AB$Sales Header] t5
WHERE EXISTS (SELECT 1
FROM [dbo].[MNO International AB$Customer] t6
WHERE t5.[Bill-to Customer No_] = t6.[No_]
)
) as TempSa
但是,我认为你想要的价值是:
SELECT t1.Name,
(SELECT COUNT(t5.[Bill-to Customer No_]) as he
FROM [dbo].[MNO International AB$Sales Header] t5
WHERE EXISTS (SELECT 1
FROM [dbo].[MNO International AB$Customer] t6
WHERE t5.[Bill-to Customer No_] = t6.[No_]
) AND
t5.[Bill-to Name] = t1.Name
--------------^ correlation clause instead of `GROUP BY`
) as TempSa