SQL插入#TEMP表

时间:2016-08-15 09:29:04

标签: sql-server stored-procedures

CREATE TABLE #TEMP (Date  NVARCHAR(256),Pending NVARCHAR(256),Complete NVARCHAR(256) ,Total  NVARCHAR(256));
INSERT INTO #TEMP (Date,Pending,Total) 
SELECT DISTINCT(DATEE),'','' from E_R_MainT
GROUP BY DATEE

UPDATE #TEMP
SET Pending=(SELECT COUNT(R_ID) FROM E_R_MainT WHERE STATUS !='S_2' GROUP BY (CONVERT(char(10), HOD_DT ,126)) )
WHERE #TEMP.Date =  (SELECT DISTINCT(DATEE) from E_R_MainT
GROUP BY DATEE)

UPDATE #TEMP
SET Complete=(SELECT COUNT(R_ID) FROM E_R_MainT WHERE STATUS !='S_1' GROUP BY DATEE )
WHERE #TEMP.Date =  (SELECT DISTINCT(DATEE) from E_R_MainT
GROUP BY DATEE )

UPDATE #TEMP
SET Total=(SELECT COUNT(R_ID) FROM E_R_MainT  GROUP BY (DATEE) )
WHERE #TEMP.Date =  (SELECT DISTINCT(DATEE) from E_R_MainT
GROUP BY  DATEE
SELECT * FROM #TEMP

执行我的查询时出现此错误:

  

"子查询返回的值超过1。这是不允许的#34;

下面是我的表格来源: enter image description here

我期待这个输出: enter image description here

3 个答案:

答案 0 :(得分:1)

这里有一些令人困惑的命名,因此我怀疑在查询的某些部分显示不同的几个名称实际上是指同一列。

这里不需要临时表 - 只需使用合适的聚合:

SELECT
    DATEE,
    SUM(CASE WHEN Status = 's_1' THEN 1 ELSE 0 END) as Pending,
    SUM(CASE WHEN Status = 's_2' THEN 1 ELSE 0 END) as Complete,
    COUNT(*)
FROM E_R_MainT
GROUP BY DATEE

答案 1 :(得分:0)

这部分给你带来了问题..

WHERE #TEMP.Date =  (SELECT DISTINCT(DATEE) from E_R_MainT
GROUP BY DATEE)

更改为..更好,不需要明确和分组

WHERE #TEMP.Date  in  (SELECT (DATEE) from E_R_MainT

答案 2 :(得分:0)

您的示例代码:

UPDATE #TEMP
SET Total=(SELECT COUNT(R_ID) FROM E_R_MainT  GROUP BY (DATEE) )
WHERE #TEMP.Date =  (SELECT DISTINCT(DATEE) from E_R_MainT
GROUP BY  DATEE
SELECT * FROM #TEMP

此内容

SELECT COUNT(R_ID) FROM E_R_MainT  GROUP BY (DATEE) )
WHERE #TEMP.Date =  (SELECT DISTINCT(DATEE) from E_R_MainT
GROUP BY  DATEE

不是只返回一个,我认为它返回多个值,检查上面的所有查询看起来像那样。我确定这是给你错误的原因。