仅计算特殊行的数据

时间:2017-09-28 18:35:52

标签: sql sql-server

我有桌子:

~$ which jekyll
/usr/local/bin/jekyll
~$ which ruby
/usr/local/bin/ruby
~$ which grunt
[URL]/.npm-packages/bin/grunt
~$ which gem
/usr/local/bin/gem
~$ which node
/usr/local/bin/node

有必要显示那些' OperationID'每个' ID'

中都有

实施例。输出:

ID    count  OperationID 
100   111       1
100    55       2
100    55       3
100    66       4 
99     69       1
99     33       2
99     11       14
98     33       1
98     47       2

也许连接表本身有帮助?但它不起作用......

4 个答案:

答案 0 :(得分:1)

你可以使用它。

DECLARE @MyTable TABLE ( ID INT, [count] INT,OperationID  INT)

INSERT INTO @MyTable
VALUES
(100,111,1),
(100,55,2),
(100,55,3),
(100,66,4 ),
(99,69,1),
(99,33,2),
(99,11,14),
(98,33,1),
(98,47,2)

SELECT  * 
FROM @MyTable 
WHERE 
    OperationID IN 
    (SELECT 
        OperationID 
    FROM @MyTable
    GROUP BY OperationID
    HAVING COUNT(*) = (SELECT COUNT(DISTINCT ID) FROM @MyTable)
 )

结果:

ID          count       OperationID
----------- ----------- -----------
100         111         1
100         55          2
99          69          1
99          33          2
98          33          1
98          47          2

答案 1 :(得分:1)

好的,您可以尝试这一点,但数据集中有一些注意事项,例如,如果行没有通用的OpID ,那该怎么办? / p>

declare @tbl table (ID int,Cnt int, OperationID int)
insert into @tbl
select  100,111,1 union
select  100, 55,2 union
select  100, 55,3 union
select  100, 66,4 union 
select  99 , 69,1 union
select  99 , 33,2 union
select  99 , 11,14 union
select  98 , 33,1 union
select  98,47,2

 select * from @tbl where OperationID in (
 select OperationID from @tbl
 where id in (
select a.id from 
(
select top 1 id, count (distinct OperationID) as opCnt from @tbl
group by id
order by opCnt
) a
)
)

结果

98  33  1
98  47  2
99  33  2
99  69  1
100 55  2
100 111 1

答案 2 :(得分:0)

我确信这不是最佳方式。

with cte1 as (
select distinct id
from Operations
), 

cte2 as (
select distinct operationID
from Operations
)
, cte3 as (
select *
from cte1 cross join cte2
)

SELECT *
FROM operations
WHERE operationid NOT IN(

SELECT cte3.operationid
FROM operations a
right JOIN cte3 ON cte3.id = a.id
AND cte3.operationid = a.operationid
WHERE a.id IS NULL) 

答案 3 :(得分:0)

你可以尝试一下

DECLARE @table TABLE ( id INT, cnt INT, operationid INT ) 

INSERT INTO @table VALUES
 (100,111 , 1 ) 
,(100, 55 , 2 ) 
,(100, 55 , 3 ) 
,(100, 66 , 4 ) 
,(99 , 69 , 1 ) 
,(99 , 33 , 2 ) 
,(99 , 11 , 14)  
,(98 , 33 , 1 )  
,(98 , 47 , 2 )

;WITH cte
AS (
SELECT
    Count(distinct id)  TotalId
FROM
    @table
)
,cte1  as 
(select 
 operationid
,Count( distinct id)  operationid_By_Id
FROM
    @table
Group by
operationid )
SELECT * From 
@table c
WHERE EXISTS (
SELECT 1 FROM (
    SELECT 
        * 
    FROM cte1 A 
    WHERE EXISTS (SELECT 1 FROM cte b WHERE a.operationid_By_Id = b.TotalId) 
    ) d where d.operationid = c.operationid)
Order by id desc , operationid