为什么SQL查询会引发终止错误

时间:2014-05-19 17:39:12

标签: sql sql-server

我有一个SQL表,其中包含一些数据。我有另一个表,它获取这些数据并将其保存到新表:

TRUNCATE TABLE database.dbo.[table2]

INSERT INTO [database].[dbo].[table2]
SELECT CONVERT(VARCHAR(10), DATEADD(day, -(DATEPART(dw, GETDATE()) + @@DATEFIRST) % 7, DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)), 101) AS [Date], -- ADD YESTERDAY'S DATE
    SUM([EMR ORDERS]) AS LastWeekEMROrders,
    SUM([ACCESSIONED LAB ORDERS]) AS LastWeekAccLabOrders,
    SUM([LAB_RESULT]) AS LastWeekLabResults,
    ((SELECT [EMR ORDERS] FROM [database].[dbo].[originaltable]) - (SELECT [ACCESSIONED LAB ORDERS] FROM [database].[dbo].[originaltable])) AS [LastWeekPendingProcessing]
FROM [database].[dbo].[originaltable]
WHERE
    [Date] >= DATEADD(day, -((DATEPART(dw, GETDATE()) + @@DATEFIRST) % 7) - 6,
              DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)) --PREVIOUS SUNDAY
    AND
    [Date] <= DATEADD(day, -(DATEPART(dw, GETDATE()) + @@DATEFIRST) % 7,
              DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)) --PREVIOUS SATURDAY

这是我得到的错误:

Msg 512, Level 16, State 1, Line 3
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

基本上它应该从原始表中获取数据并根据周计算的查询。它工作正常,但我不确定为什么会发生...

请帮我解决问题。

原始表格如下:

enter image description here

1 个答案:

答案 0 :(得分:2)

答案:因为以下查询会返回多行:

(
(SELECT [EMR ORDERS] FROM [database].[dbo].[originaltable]) 
- 
(SELECT [ACCESSIONED LAB ORDERS] FROM [database].[dbo].[originaltable])
) AS [LastWeekPendingProcessing]

这是因为[database].[dbo].[originaltable]有两行或更多行。

解决方案:

[1] 使用谓词来过滤行:

(SELECT [EMR ORDERS] FROM [database].[dbo].[originaltable] WHERE <predicate>) 

[2] 使用聚合函数:

(SELECT SUM/COUNT/...([EMR ORDERS] FROM [database].[dbo].[originaltable]) 

注意:您可以使用

(SELECT [EMR ORDERS] - [ACCESSIONED LAB ORDERS] FROM [database].[dbo].[originaltable] WHERE ...) 

(SELECT SUM/...([EMR ORDERS] - [ACCESSIONED LAB ORDERS]) FROM [database].[dbo].[originaltable] WHERE ...)