【发布时间】:2016-05-18 12:51:24
【问题描述】:
我需要从 typeTable 的“源”列中获取子字符串,并能够从该列中获取每个区域的统计信息。一行看起来像“server001[en-US]”。然后打印每个国家的统计数据。也就是说,我需要每个国家/地区的 countForType 和 totalForType。
所以,我相信获取所有 server001 调用并按国家/地区对它们进行分组是我正在寻找的。p>
到目前为止,我的查询如下所示:
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
有人可以告诉我我是否在正确的轨道上,或者是否应该完全重写?任何指针表示赞赏。
【问题讨论】:
-
这是一个简单的编程问题,请google并了解SQL Server中的SUBSTRING功能。
-
我知道如何使用 substring 函数。请完整阅读帖子。
-
我完整阅读了这篇文章。由于您已经展示了 GROUP BY 子句的知识,我假设您不知道如何获取子字符串。您能否更清楚地了解这个问题的哪一部分您不知道该怎么做?
-
同意@TabAlleman 关于重复但不同意子字符串,因为 OP 确实知道如何使用它。他唯一的问题是他没有使用 group by 的 substring 部分。
-
不是您问题的答案,但要小心将 NOLOCK 提示到处乱扔。至少要确保你完全理解它的作用,它不是一个神奇的更快的按钮。它有一些非常严重的副作用,大多数人都懒得去理解。 blogs.sqlsentry.com/aaronbertrand/bad-habits-nolock-everywhere
标签: sql sql-server group-by substring