如何通过家庭代码查询组

时间:2014-11-24 10:04:16

标签: sql sql-server group-by

我应该编写一个查询来计算一个列的总和,其中原因代码就像一个数字。所以我有这张桌子

TableX的:

 ------------------------
| ReasoneCode | Duration |
|------------------------|
| 201         | 27512    |
| 202         | 4372     |
| 100         | 10322    |
| 301.12      | 1        |
| 302.06      | 34       |
| 305         | 12       |
 ------------------------

现在我想要一个这样的结果:

 ------------------------
| ReasoneCode | Duration |
|------------------------|
| 200         | 31884    |
| 100         | 10322    |
| 300         | 47       |
 ------------------------

所以我尝试编写此查询但未找到正确的

SELECT ReasonCode, SUM(Duration)
FROM TableX    
GROUP BY ReasonCode

你能帮助我吗?


我尝试使用此解决方案。 通过此查询,我删除所有'。'从第一栏

SELECT CAST(LEFT(replace(ReasonCode, '.', ''), (CHARINDEX('.', replace(ReasonCode, '.', ''), 1) + 4)) AS DECIMAL(14, 0)) as Data, SUM(Duration)
FROM TableX
GROUP BY CAST(LEFT(replace(ReasonCode, '.', ''), (CHARINDEX('.', replace(ReasonCode, '.', ''), 1) + 4)) AS DECIMAL(14, 0))

现在我尝试根据reasoneCode Family的结果为group编写另一个查询。 此查询的结果是:

 ------------------------
| ReasoneCode | Duration |
|------------------------|
| 201         | 27512    |
| 202         | 4372     |
| 100         | 10322    |
| 30112       | 1        |
| 30206       | 34       |
| 305         | 12       |
 ------------------------

我可以把这个结果放到临时表中,然后从这个临时表中选择

SELECT
    CAST(CAST(ReasonCode as decimal(8,2)) as int) / 100 * 100 as roundedCode,
    SUM(Duration)
FROM @TemporaryTable    
GROUP BY CAST(CAST(ReasonCode as decimal(8,2)) as int) / 100 * 100

现在结果如下:

     ------------------------
    | ReasoneCode | Duration |
    |------------------------|
    | 200         | 31884    |
    | 100         | 10322    |
    | 3000        | 35       |
    | 305         | 12       |
     ------------------------

只有一个错误,它不是300和3000分组。

4 个答案:

答案 0 :(得分:0)

SELECT cast(ReasonCode as int) / 100 * 100 as roundedCode, SUM(Duration)
FROM TableX    
GROUP BY roundedCode

答案 1 :(得分:0)

假设您想要按百的倍数进行分组,并且两列都是数字,这就是它的完成方式。

SELECT round(round(ReasonCode)/ 100)* 100 as roundedCode,SUM(Duration) 来自TableX
GROUP BY roundedCode

答案 2 :(得分:0)

试试这个:

SELECT
    CAST(CAST(ReasonCode as decimal(15,5)) as int) / 100 * 100 as roundedCode,
    SUM(Duration)
FROM TableX    
GROUP BY roundedCode

答案 3 :(得分:0)

试试这个

如果ReasonCode是NUMERIC数据类型

SELECT (ReasonCode-(ReasonCode%100)), SUM(Duration)
FROM #Table    
GROUP BY (ReasonCode-(ReasonCode%100))

如果ReasonCode是NVARCHAR

SELECT (CONVERT(NUMERIC(22,6),ReasonCode)-(CONVERT(NUMERIC(22,6),ReasonCode)%100)), SUM(Duration)
FROM #Table    
GROUP BY (CONVERT(NUMERIC(22,6),ReasonCode)-(CONVERT(NUMERIC(22,6),ReasonCode)%100))