加入两个计数查询

时间:2016-12-29 16:22:43

标签: join count

所以这就是我所处的位置(这完全符合需要)。然而,这只是该项目的第一步。因此,我们的目标是让这个查询的结果通过ODBC显示在第一页上,以便excel(从来没有这样做,因此需要做大量的研究)。一旦在excel中显示,用户将能够输入日期范围...让我们说A1或B1(尚不确定设计)。所以到目前为止,这真的很棒。所以现在我希望制作第二张表,其中包含更多信息,然后失败/成功。第二张纸将完全按照第一张纸显示更多细节。这只适用于失败。

SELECT Sum(case when status = 6 then 1 else 0 end) as Failed,
       Sum(case when status = 9 then 1 else 0 end) as Successful,
   UniqueID
Into #tempsheet1
FROM Documents
WHERE ownerID = 467
and status in (6,9)
and CreationTime between @StartDate and @EndDate
Group By UniqueID

Select D.UniqueID, FromName, ToName, CreationTime,
cast(CreationTime as date) as CreationDate, cast(CreationTime as date) as CreationTime,
ErrorCode, ElapsedSendTime, RemoteID
From #tempsheet1 ts1
Inner Join Documents D On
D.UniqueID = ts1.UniqueID
and [Status] = 9

3 个答案:

答案 0 :(得分:1)

SELECT A.Failed,B.Successful  --before it is '*' which means 'all columns'
FROM 
(
SELECT COUNT([Status]) as Failed, 1 as JoiningValue
    FROM Documents
    Where ownerid = '467'
    and [Status] = '6') as A

INNER JOIN

(
SELECT COUNT([Status]) as Successful, 1 as JoiningValue
    FROM Documents
    Where ownerid = '467'
    and [Status] = '9') as B

ON B.JoiningValue = A.JoiningValue

答案 1 :(得分:1)

您可以使用条件聚合和总和与计数...

SELECT Sum(case when status = 6 then 1 else 0 end) as Failed,
       Sum(case when status = 9 then 1 else 0 end) as Successful,
       cast(CreationTime as date) CreationDate
FROM Documents
WHERE ownerID = 467
  and status in (6,9)
  and CreationDate between @StartDate and @EndDate
GROUP BY cast(CreationTime as date) CreationDate
ORDER BY cast(CreationTime as date) descending

由于两个查询都使用文档表和相同的ownerID过滤器,因此我们只能在where子句中过滤owerID。我在caluse的地方添加了6,9的状态,因为我们可能有很多其他的状态我们不关心,为什么还要费心去评估呢?

总和(情况评估状态,当6将计数器设置为1时失败,否则它将计数器设置为0)这样,所有1和0的总和将导致失败或成功的“计数”。

答案 2 :(得分:0)

您可以SELECT这两个查询,然后您可以在一个表中获取该值。

SELECT 
(SELECT COUNT([Status]) as Failed
into #tempfailed
FROM Documents
Where ownerid = '467'
and [Status] = '6') sa FAILED,
(SELECT COUNT([Status]) as Successful
FROM Documents
Where ownerid = '467'
and [Status] = '9') as Sucess