使用不同的搜索条件加入多个查询

时间:2013-08-12 19:52:35

标签: sql tsql sql-server-2008-r2

我有4个查询与最后一个条件子句的例外相同。我试图找到一种方法将这4个浓缩为1,如果可能的话。目前,我们编写的程序通过4个存储过程调用这4个语句,但如果我可以进行1个返回全部4个的调用,那就太好了。以下是声明的大部分内容:

SELECT SUM(PausedTime) AS PausedMode
FROM UsageStats
WHERE StartDate >= CONVERT(VARCHAR(8), @StartDate, 112) AND  StopDate < CONVERT(VARCHAR(8), @EndDate, 112)
AND LocationID = @LocationID
AND SystemID = @SystemID
AND PlayingArea = @PlayingArea
AND PausedTime > 0

我还有3个以上,唯一改变的是SUM计算中的字段(所有SUM字段的类型为int):

SUM(PlayModeTime) AS PlayModeTime
SUM(RecordModeTime) AS RecordModeTime
SUM(ReplayModeTime) AS ReplayModeTime

和最后AND条件     和PlayModeTime&gt; 0     AND RecordModeTime&gt; 0     AND ReplayModeTime&gt; 0

我尝试在select子句中使用CASE语句,但失败了:

SELECT
    playMode = (CASE WHEN PlayModeTime > 0 THEN SUM(PlayModeTime) END),
    pausedMode = (CASE WHEN PausedTime > 0 THEN SUM(PausedTime) END),
    recordMode = (CASE WHEN RecordModeTime > 0 THEN SUM(RecordModeTime) END),
    replayMode = (CASE WHEN ReplayModeTime > 0 THEN SUM(ReplayModeTime) END)
FROM UsageStats
WHERE StartDate >= CONVERT(VARCHAR(8), @StartDate, 112) AND  StopDate < CONVERT(VARCHAR(8), @EndDate, 112)
AND LocationID = @LocationID
AND SystemID = @SystemID
AND PlayingArea = @PlayingArea
GROUP BY PlayModeTime, PausedTime, RecordModeTime, ReplayModeTime

我想得到这样的东西:

PlayModeTime   | PausedMode  | RecordModeTime  | ReplayModeTime
---------------------------------------------------------------
 200              340            10               55

感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

我不明白为什么你需要这些条件,因为SUM在值为0时会加零。你不能只是SUM你的所有专栏吗?:

SELECT
    playMode = SUM(PlayModeTime),
    pausedMode = SUM(PausedTime),
    recordMode = SUM(RecordModeTime),
    replayMode = SUM(ReplayModeTime)
FROM UsageStats
WHERE StartDate >= CONVERT(VARCHAR(8), @StartDate, 112) 
AND StopDate < CONVERT(VARCHAR(8), @EndDate, 112)
AND LocationID = @LocationID
AND SystemID = @SystemID
AND PlayingArea = @PlayingArea

答案 1 :(得分:0)

您需要在案例陈述之外移动总和:

SELECT
    playMode = SUM(CASE WHEN PlayModeTime > 0 THEN PlayModeTime ELSE 0 END),
    pausedMode = SUM(CASE WHEN PausedTime > 0 THEN PausedTime ELSE 0 END),
    recordMode = SUM(CASE WHEN RecordModeTime > 0 THEN RecordModeTime ELSE 0 END),
    replayMode = SUM(CASE WHEN ReplayModeTime > 0 THEN ReplayModeTime ELSE 0 END)
FROM UsageStats
WHERE StartDate >= CONVERT(VARCHAR(8), @StartDate, 112) AND  StopDate < CONVERT(VARCHAR(8), @EndDate, 112)
AND LocationID = @LocationID
AND SystemID = @SystemID
AND PlayingArea = @PlayingArea
GROUP BY PlayModeTime, PausedTime, RecordModeTime, ReplayModeTime

原因是将针对每一行评估案例。在您的示例中,您将获取列的总和,但仅限于该行。

这仅与Lamak上面的答案不同,因为它会将负值视为总和中的零。