SQL Server How to count the number of columns based on one column from a table SQL

iih3973s  于 2023-11-16  发布在  其他
关注(0)|答案(3)|浏览(125)

Below is the table in SQL Server. I want to calculate the count of same ERR_CD columns based on threshold and insert in a temp table.
| PK_ID | ERR_CD | ERR_THRESHOLD |
| ------------ | ------------ | ------------ |
| 1 | 123 | 5 |
| 2 | 123 | 5 |
| 3 | 123 | 5 |
| 4 | 123 | 5 |
| 5 | 123 | 5 |
| 6 | 123 | 5 |
| 7 | 456 | 2 |
| 8 | 456 | 2 |
| 9 | 789 | 10 |

So my output should be like below eliminating the rows which doesn't meet the threshold.

PK_IDERR_CDERR_THRESHOLD
11235
21235
31235
41235
51235
61235
74562
84562

How can I do this in SQL Server?

4dbbbstv

4dbbbstv1#

Here is one solution:

with cte as (
  select * , count(*) over (partition by ERR_CD) cnt 
  from tablename
)

select * from cte where cnt >= ERR_THRESHOLD
xuo3flqw

xuo3flqw2#

This is basically what eshirvana said, so give credit where credit is due. I just wanted to expand on the explanation a bit.

You can use window function like count without a group by if you have an over clause. The result is you'll get whatever the result of the window function would be, replicated over every row to which it is applied.

drop table if exists #data
create table #data
(
    PK_ID int,
    ERR_CD char(3),
    ERR_THRESHOLD tinyint
)

insert into #data
values
    (1, '123', 5),
    (2, '123', 5),
    (3, '123', 5),
    (4, '123', 5),
    (5, '123', 5),
    (6, '123', 5),
    (7, '456', 2),
    (8, '456', 2),
    (9, '789', 10)

So the first part is to get that count of all rows across each ERR_CD

select 
    PK_ID,
    ERR_CD,
    ERR_THRESHOLD, 
    CountOfRowsPerErrCd = count(1) over (partition by ERR_CD)
from #data

You can see that this gives you the count of errors for each ERR_CD , and now all you have to do is write a simple WHERE clause to handle that. Unfortunately, you can't use window function directly in a WHERE clause, so you have to break out the query above into a subquery or a CTE, and then select from that.

So in its final form you get:

;with src as
(
    select 
        PK_ID,
        ERR_CD,
        ERR_THRESHOLD, 
        CountOfRowsPerErrCd = count(1) over (partition by ERR_CD)
    from #data
)
select *
from src
where ERR_THRESHOLD <= CountOfRowsPerErrCd
jecbmhm3

jecbmhm33#

Here is the solution using SQL server.

with thresold as
(
    select
        pk_id , 
        err_cd , 
        err_threshold , 
        count(pk_id) over(partition by err_cd) as [count] 
    from err
)
select pk_id , err_cd , err_threshold from thresold as a where [count] >= err_threshold;

相关问题