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_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 |
How can I do this in SQL Server?
3条答案
按热度按时间4dbbbstv1#
Here is one solution:
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 agroup by
if you have anover
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.So the first part is to get that count of all rows across each
ERR_CD
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 simpleWHERE
clause to handle that. Unfortunately, you can't use window function directly in aWHERE
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:
jecbmhm33#
Here is the solution using SQL server.