SQL Server:基于列的子串的组查询

时间:2016-02-08 18:31:52

标签: sql sql-server group-by substring

我需要从列'来源'中获取子字符串。来自typeTable,能够从该列的每个区域获取统计数据。一行看起来像' server001 [en-US]'。然后打印每个国家/地区的统计信息。也就是说,我需要每个国家/地区的countForType和totalForType。

所以,我相信获取所有server001电话并按国家/地区分组是我正在寻找的。

到目前为止,我的查询看起来像这样:

        use thedatabase;

        declare @fromDate datetime = '2016-02-01 00:00:00.000';
        declare @toDate datetime = '2016-02-02 23:59:59.999';
        declare @source varchar(15) = 'server001';

        DECLARE @countForType bigint;
        DECLARE @totalForType decimal(30,8);

        DECLARE @country varchar(10);

        SELECT  @countForType = count(*),
                @totalForType = SUM(typeTable.amount),
                @country = 
                    case
                    when (charindex('[', typeTable.source) > 0 and charindex(']', typeTable.source) > 0)
                    then substring(typeTable.source, charindex('[', typeTable.source) +1, (charindex(']', typeTable.source) - 1) - charindex('[', typeTable.source))
                    else null
                    end

        FROM theTypeTable typeTable (nolock)
        WHERE typeTable.startDate > @fromDate
        AND typeTable.startDate < @toDate
        AND typeTable.source like @source 
        GROUP BY typeTable.source;  -- i believe the issue may be here -- source is the entire string 'server001[en-US]'.  I need to group and provide stats per country, which is a substring of source.


    --Print report:
    PRINT 'countForType: ' + CAST(@countForType AS VARCHAR);
    PRINT 'totalForType: ' + CAST(@totalForType AS VARCHAR);
    --for each country, print the amounts/ percentages etc...
    PRINT 'country: ' + CAST (@country AS VARCHAR);

报告本身看起来像:

countForType: 104
totalForType: 110000.00000000

country: en-US
countForType: 55
totalForType: 95000.00000000

country: de-CH
countForType: 25
totalForType: 5000.00000000

country: tr-TR
countForType: 30
totalForType: 10000.00000000

如果我在这里正确的轨道,或者是否应该完全重写,有人可以告诉我吗?任何指针都表示赞赏。

1 个答案:

答案 0 :(得分:2)

你已经有了代码。 GROUP BY您用于获取国家/地区的CASE声明:

GROUP BY                     case
                    when (charindex('[', typeTable.source) > 0 and charindex(']', typeTable.source) > 0)
                    then substring(typeTable.source, charindex('[', typeTable.source) +1, (charindex(']', typeTable.source) - 1) - charindex('[', typeTable.source))
                    else null
                    end

顺便说一下,你的代码不会做你的评论所说的你想做的事情:

--Print report:
PRINT 'countForType: ' + CAST(@countForType AS VARCHAR);
PRINT 'totalForType: ' + CAST(@totalForType AS VARCHAR);
--for each country, print the amounts/ percentages etc...
PRINT 'country: ' + CAST (@country AS VARCHAR);

您将数据存储在标量变量中,这意味着查询的执行只会将一个值存储到每个变量中。它不允许您遍历每个结果。要以您在问题中指定的确切格式获得输出,您需要使用WHILE循环或CURSOR。

但是,我怀疑你是否真的需要SQL来输出那种格式。让SQL返回结果集并在前端应用程序中格式化输出会更好。