2

我想根据返回的 2 个字段对 select 的结果进行计数,并且我使用 group by 子句来执行此操作。尽管我使用 substring 和 patindex 修改了返回的字段之一,以获取结果中冒号后的所有内容,因此我最终得到一个包含单词“paper”或“online”的列。我想计算论文和在线结果的数量,但我得到的结果是基于该领域的原始内容而不是基于我修改的内容。这就是我现在正在做的事情:

select field1, field2, 
       case when substring(field3, patindex('%:%',field3)+1, 6) = 'Paper' then 'paper' 
   else 'online' end, count(field3) 'Count'
from theTable
group by field2, field1, field3
order by field2, field1

我也试过:

select field1, field2, 
       count(case when substring(field3, patindex('%:%',field3)+1, 6) = 'Paper' then 'paper' 
   else 'online' end) 'Count'
from theTable
group by field2, field1, field3
order by field2, field1

我需要做什么才能获得我所追求的计数?

4

2 回答 2

2
SELECT  field1,
        field2,
        SUM(CASE WHEN substring(field3, patindex('%:%', field3) + 1, 6) = 'Paper'
                THEN 1
                ELSE 0
        END) totalPaper,
        SUM(CASE WHEN substring(field3, patindex('%:%', field3) + 1, 6) <> 'Paper'
                THEN 1
                ELSE 0
        END) totalOnline,
        count(field3) TotalCount
FROM    theTable
GROUP   BY field2, field1
ORDER   BY field2, field1

感谢mellamokb的小提琴链接。:D

于 2013-04-05T12:41:17.557 回答
1

计算什么取决于GROUP BY. 所以你需要 group by 子句中的逻辑:

select field1, field2, 
   case when substring(field3, patindex('%:%',field3)+1, 6) = 'Paper'
       then 'paper'  else 'online' end 'Type', count(field3) 'Count'
from theTable
group by field2, field1, case when substring(field3,
       patindex('%:%',field3)+1, 6) = 'Paper' then 'paper'  else 'online' end
order by field2, field1

演示:http ://www.sqlfiddle.com/#!3/f5d13/3

于 2013-04-05T12:40:52.130 回答