【问题标题】:Use of sum and count inside a case statement in sql在sql中的case语句中使用sum和count
【发布时间】:2024-01-13 19:13:01
【问题描述】:
select req.code ,res.code,
case
( 
when (req.code==res.code) then 'pass'
when (req.code<>res.code) then 'fail'
/*....2 more case 'when' 'then' statements here*/
end ) result,

req.country ,res.country,

case (when then staments as above)result,
/*.......case stmts upto 70 statemnts*/
from requesttable req full outer join responsetable res on
req.id=res.id 
and ....some conditions.

谁能告诉我如何对每一列求和并同时显示两个表的每一列中的总和以及记录数并在我的查询中显示计数?

我的结果应该是这样的

code  code1  result  sum     sum1    equivalence country country1 result1  sum    sum1
100   100    pass    200000  25000   fail        ind     aus      fail     800000 800000

equivalence
pass

我正在尝试准备一份连接两个表格的报告。我正在使用多个案例语句来完成此操作。我想在一个报告中同时显示两个表的每列的总和和每列的计数。我的查询属于以下类型。

【问题讨论】:

  • 显示您想要的输出非常有用,但如果我们也有您尝试从中获取的 输入数据 的样本,它会更加有用获得该输出。

标签: sql sum case


【解决方案1】:

我认为这正是您想要的。对于显示在该行上的代码和国家/地区值,它将为您提供所显示组合的通过和失败帐户,并且您将在定义聚合的列上具有唯一性。

Select  req.code, 
        res.code,
        Sum(Case When req.code = res.code) Then 1 Else 0 End) As [Pass],
        Sum(Case When req.code <> res.code) Then 1 Else 0 End) As [Fail],
        req.country, 
        res.country,
        Sum(Case When req.country = res.country) Then 1 Else 0 End) As [Pass],
        Sum(Case When req.country <> res.country) Then 1 Else 0 End) As [Fail]
From    requesttable req
Full    Outer Join responsetable res
        On  req.id = res.id
Where   ...
Group   By  req.code,
            res.code,
            req.country,
            res.country

【讨论】:

    最近更新 更多