如何在Select中过滤其他列来计算相同的列

时间:2014-12-26 09:00:23

标签: sql-server

我们如何在SQL Server中按过滤器计算相同的列:

此处表:

id CodeType Code 
1   I        C001
1   I        M002
2   I        C002 
2   M        M003
3   I        C002 
3   M        M003

Sql输出应该是这样的:

Count WHEN CodeType I and Code  C001 with M002  :1
Count WHEN CodeType I and Code  C002 with M003  :2

我们如何使用SQL Server执行此操作

2 个答案:

答案 0 :(得分:0)

尝试使用COUNT(*)OVER(Partition by)

create table #test(id int,CodeType char(1),Code char(4))

insert into #test values(1,'I','C002')
insert into #test values(2,'M','M003')
insert into #test values(3,'M','M003')

select id,CodeType,Code,count(*) over (partition by codetype,code) as cnt from #test

答案 1 :(得分:0)

让我们制作示例数据:

DECLARE @MyTable TABLE
( 
    id INT,
    CodeType VARCHAR(1),
    Code VARCHAR(10)
)

INSERT INTO @MyTable
( id, CodeType, Code )
VALUES
(1,   'I',        'C001'),
(1,   'I',        'M002'),
(2,   'I',        'C002'),
(2,   'M',        'M003'),
(3,   'I',        'C002'),
(3,   'M',        'M003');

现在我们有了数据,看起来你想要为每个C记录找到相应的M记录(基于ID),一旦你得到这些集合,你就会寻找重复数据。您还在检查C记录类型是否为“我”

SELECT c.CodeType, c.Code, m.Code, COUNT(*) AS GrpCnt
FROM @MyTable c
INNER JOIN @MyTable m
    ON c.id = m.id
    AND c.Code LIKE 'C%'
    AND m.Code LIKE 'M%'
WHERE c.CodeType = 'I'
GROUP BY c.CodeType, c.Code, m.Code

这是输出:

CodeType    Code    Code    GrpCnt
I   C001    M002    1
I   C002    M003    2

希望这会有所帮助......