求SQL合并……
我写的2个sql,查询的数据都一样,第2条SQL 就是多了一个 WHERE 条件,看图
在贴语句:
SELECT SUM(c.TimeLength) AS planCountTime,a.ProjectID FROM dbo.T_WBS AS a
JOIN dbo.T_Task AS b ON a.WBSID = b.WBSID
JOIN dbo.T_TaskDetail AS c ON b.TaskID = c.TaskID
GROUP BY a.ProjectID
SELECT SUM(c.TimeLength) AS planCountTime,a.ProjectID FROM dbo.T_WBS AS a
JOIN dbo.T_Task AS b ON a.WBSID = b.WBSID
JOIN dbo.T_TaskDetail AS c ON b.TaskID = c.TaskID
WHERE c.TaskDate<GETDATE()-1
GROUP BY a.ProjectID
基本都一样,我想把他们合并下 可是数据就不对了:
SQL :
SELECT SUM(c.TimeLength) AS planCountTime ,
SUM(d.TimeLength) AS shouldWorkTime ,
a.ProjectID
FROM dbo.T_WBS AS a
JOIN dbo.T_Task AS b ON a.WBSID = b.WBSID
LEFT JOIN dbo.T_TaskDetail AS c ON b.TaskID = c.TaskID
LEFT JOIN dbo.T_TaskDetail AS d ON ( d.TaskID = b.TaskID AND d.TaskDate < GETDATE() - 1 )
GROUP BY a.ProjectID
求大神指点下,看看这两句sql怎么合并不需要多写那么多行重复SQL !
------最佳解决方案--------------------你的意思是这样?
SELECT SUM(c.TimeLength) AS planCountTime,a.ProjectID,
SUM(CASE WHEN c.TaskDate<GETDATE()-1 THEN C.TimeLength ELSE 0 END)
FROM dbo.T_WBS AS a
JOIN dbo.T_Task AS b ON a.WBSID = b.WBSID
JOIN dbo.T_TaskDetail AS c ON b.TaskID = c.TaskID
GROUP BY a.ProjectID
------其他解决方案--------------------SELECT SUM(c.TimeLength) AS planCountTime,a.ProjectID FROM dbo.T_WBS AS a
JOIN dbo.T_Task AS b ON a.WBSID = b.WBSID
JOIN dbo.T_TaskDetail AS c ON b.TaskID = c.TaskID
GROUP BY a.ProjectID
SELECT SUM(c.TimeLength) AS planCountTime,a.ProjectID FROM dbo.T_WBS AS a
JOIN dbo.T_Task AS b ON a.WBSID = b.WBSID
JOIN dbo.T_TaskDetail AS c ON b.TaskID = c.TaskID
WHERE c.TaskDate<GETDATE()-1
GROUP BY a.ProjectID
------------------------
DECLARE @SQL1 VARCHAR(1000),@SQL2 VARCHAR(1000)
SET @SQL1='SELECT SUM(c.TimeLength) AS planCountTime,a.ProjectID FROM dbo.T_WBS AS a
JOIN dbo.T_Task AS b ON a.WBSID = b.WBSID
JOIN dbo.T_TaskDetail AS c ON b.TaskID = c.TaskID '
SET @SQL2=' GROUP BY a.ProjectID '
--1、
EXEC(@SQL1 + @SQL2)
2、
EXEC(@SQL1 +' WHERE c.TaskDate<GETDATE()-1 '+ @SQL2)
------其他解决方案--------------------SELECT SUM(c.TimeLength) AS planCountTime,a.ProjectID FROM dbo.T_WBS&n