SQL数据分组

时间:2015-12-10 11:09:34

标签: sql sql-server

我希望有人能够帮助我(或指出我正确的方向)解决以下问题。我正在考虑将大量代码分组为仅3位数,确保如果参与者具有代码122.2和122.3,则它将计为一次而不是两次。

数据示例:

Participant | group_code
1           | 1223
1           | 1224
1           | 1123
2           | 1012
2           | 0123

当前代码:

SELECT  (left(group_code, 3)) as Group, count(left(group_code, 3)) as occurrence 
from testDB
group by left(group_code, 3)

我怀疑在分组时我需要在参与者ID上使用唯一元素,但我不太确定。

当前结果:

使用当前数据示例,结果如下。 122有2次出现 112有1次发生 101有1次发生 012有1次出现

预期结果:

122有1次出现 112有1次发生 101有1次发生 012有1次出现

问题:是否可以更改当前代码,以便在单个参与者多次出现3位数值时,例如111.1,111.2,111.3和111.4,使用上面的代码将提供out 111发生了4次。但是,我只想说它出现过一次,因为我只对3位数(而不是第4位)感兴趣。

非常感谢

4 个答案:

答案 0 :(得分:1)

Create Table #T(Id int, Value decimal(16,2))

Insert into #T
Values(1,122.2),(1,122.3),(2,122.2)


Select Id,ROUND(Value,0)
from #T
Group By Id,ROUND(Value,0)

答案 1 :(得分:1)

试试这个。

declare @t table ( group_code varchar(15))

insert into @t values ('122.2') ,('122.3' ) ,( '122.4' ) ,( '112.6'),( '112.0') , ( '119.1')

   SELECT  (left(group_code, 3)) as Grop, 
        count(left(group_code, 3)) as occurrence 
    from @t
        group by left(group_code, 3) 

select * from
(

    SELECT  (left(group_code, 3)) as Grop, 
        count(left(group_code, 3)) as occurrence 
    from @t
        group by left(group_code, 3) 
) a
join @t t on a.Grop  = left(t.group_code, 3)

答案 2 :(得分:0)

试试这个

SELECT  (left(group_code, 3)) as Group, count(*) as occurrence 
from testDB
group by left(group_code, 3)

答案 3 :(得分:0)

编辑:

根据你在问题中的最后一次编辑,它应该是:

DECLARE @tbl TABLE(Participant INT, group_code INT);
INSERT INTO @tbl VALUES
 (1,1223)
,(1,1224)
,(1,1123)
,(2,1012)
,(3,0123);

WITH WithGroupingNew AS
(
    SELECT tbl.*
          ,LEFT(CAST(tbl.group_code AS varchar(100)),3) AS NewGroupingCode
    FROM @tbl AS tbl
)
,Counted AS
(
    SELECT *
          ,ROW_NUMBER() OVER(PARTITION BY NewGroupingCode ORDER BY group_code) AS Counter
    FROM WithGroupingNew
)
SELECT *
FROM Counted 
WHERE Counter=1

在编辑之前,这可能很有用......

通过此CTE,您将获得包含所需信息的字段:

DECLARE @tbl TABLE(Participant INT, group_code INT);
INSERT INTO @tbl VALUES
 (1,1223)
,(1,1224)
,(1,1123)
,(2,1012)
,(3,0123);

WITH WithGroupingNew AS
(
    SELECT tbl.*
          ,LEFT(CAST(tbl.group_code AS varchar(100)),3) AS NewGroupingCode
    FROM @tbl AS tbl
)
SELECT * FROM WithGroupingNew

结果

Participant group_code  NewGroupingCode
1           1223        122
1           1224        122
1           1123        112
2           1012        101
3           0123        123

由你决定,你要做什么:

SELECT DISTINCT NewGroupingCode FROM WithGroupingNew

或者

SELECT DISTINCT Participant,NewGroupingCode FROM WithGroupingNew

或者

SELECT *,ROW_NUMBER() OVER(PARTITION BY NewGroupingCode ORDER BY group_code)