SQL查询通过应用group by来获取计数

时间:2017-06-05 07:28:09

标签: sql sql-server

我想得到以下结果:

源表:

Cnt  A    B
4   ABC YU/FGH
5   ABC YU/DFE
5   ABC KL
2   LKP BN/ER
4   JK  RE

结果:

Cnt  A  B
9   ABC YU
5   ABC KL
2   LKP BN
4   JK  RE

在这里,我希望通过分组' B'并希望显示' B'仅记录特殊字符(/)

6 个答案:

答案 0 :(得分:0)

你可以得到你的字符串直到' /'使用 SUBSTRING

select 
count(SUBSTRING(reverse(B),0,charindex('/',reverse(B)))),
A,
SUBSTRING(reverse(B),0,charindex('/',reverse(B)))
from source_table group by B;

答案 1 :(得分:0)

Oracle的解决方案 - substr(B,0,instr(B,'/',1)-1)B

将它们放在select和groupby中

答案 2 :(得分:0)

基本上,您必须过滤掉“/”符号后面的所有字符,然后应用SUMGROUP BY。你可以在下面看到这个。内部查询过滤掉不需要的字符串,外部查询执行SUMGROUP BY

SELECT      SUM(t.Cnt), t.A, t.B
FROM        (
                SELECT      Cnt,
                            A,
                            CASE
                                WHEN CHARINDEX('/', B) > 0 THEN SUBSTRING(B, 0, CHARINDEX('/', B))
                            ELSE B
                            END AS B 

                FROM        #Tab
            ) t
GROUP BY    t.A, t.B
ORDER BY    t.A

你可以在这里看到这个 - > http://rextester.com/IQJ79191

希望这有帮助!!!

答案 3 :(得分:0)

我建议你使用这样的查询:

select 
    sum(Cnt) Cnt, 
    A, 
    left(B, charindex('/',B+'/',0)-1) B    -- Using `+'\'` will do the trick
from 
    t
group by 
    A, 
    left(B, charindex('/',B+'/',0)-1);

答案 4 :(得分:0)

使用String和CharIndex函数。

;WITH SourceTable(Cnt,A,B) AS
(
SELECT 4,'ABC','YU/FGH'UNION ALL
SELECT 5,'ABC','YU/DFE'UNION ALL
SELECT 5,'ABC','KL'  UNION ALL
SELECT 2,'LKP','BN/ER' UNION ALL
SELECT 4,'JK','RE'
)

SELECT SUM(Cnt) AS Cnt,A,CASE WHEN CHARINDEX('/',B) = 0 THEN B
                              ELSE SUBSTRING(B,0,CHARINDEX('/',B)) END AS [B] FROM SourceTable
GROUP BY A,CASE WHEN CHARINDEX('/',B) = 0 THEN B
                ELSE SUBSTRING(B,0,CHARINDEX('/',B)) END
ORDER BY Cnt DESC

答案 5 :(得分:0)

尝试此查询 -

SELECT SUM(Cnt) AS [COUNT]
    ,A
    ,CASE 
        WHEN CHARINDEX('/', B) > 0
            THEN SUBSTRING(B, 1, (CHARINDEX('/', B) - 1))
        ELSE B
        END
FROM tblSample
GROUP BY A, B
ORDER BY A, B