Some example data:
CREATE TABLE #TempTable (
ID varchar(10),
GroupCD varchar(10),
SurrogateKEY1 varchar(10),
SurrogateKEY2 varchar(10)
)
INSERT INTO #TempTable (ID, GroupCD, SurrogateKEY1, SurrogateKEY2)
VALUES
('1', 'UNK', '12345', '89225'),
('3', 'ABC', NULL, '44658'),
('3', 'DEF', NULL, '99658'),
('5', 'ABC', '09184', NULL),
('4', 'DEF', NULL, '85598'),
('1', 'GHI', '80642', '77890')
ID | GroupCD | SurrogateKEY1 | SurrogateKEY2 |
---|---|---|---|
1 | UNK | 12345 | 89225 |
3 | ABC | NULL | 44658 |
3 | DEF | NULL | 99658 |
5 | ABC | 09184 | NULL |
4 | DEF | NULL | 85598 |
1 | GHI | 80642 | 77890 |
I would like to calculate the fill rates for the SurrogateKey columns, grouped by the IDs, which I have code for:
SELECT
ID,
CAST(SUM(CASE WHEN SurrogateKEY1 IS NULL THEN 0 ELSE 1 END) / CAST(COUNT(1) AS FLOAT) * 100 AS Decimal(8,3)) AS SurrogateKEY1_fR,
CAST(SUM(CASE WHEN SurrogateKEY2 IS NULL THEN 0 ELSE 1 END) / CAST(COUNT(1) AS FLOAT) * 100 AS Decimal(8,3)) AS SurrogateKEY2_fR
FROM #TempTable
GROUP BY ID
ID | SurrogateKEY1_fR | SurrogateKEY2_fR |
---|---|---|
1 | 100.000 | 100.000 |
3 | 0.000 | 100.000 |
4 | 0.000 | 100.000 |
5 | 100.000 | 0.000 |
I'd like to expand this query so the fill rate calculation will be based on the GroupCD = 'ABC' or every other code.
I would like the output to be:
| ID | SurrogateKEY1_fR_NonABC | SurrogateKEY1_fR_ClassFilterABC | SurrogateKEY2_fR_NonABC | SurrogateKEY2_fR_ClassFilterABC |
| ------------ | ------------ | ------------ | ------------ | ------------ |
| 1 | 100.000 | 0.000 | 100.000 | 0.000 |
| 3 | 0.000 | 0.000 | 100.000 | 100.000 |
| 4 | 0.000 | 0.000 | 100.000 | 0.000 |
| 5 | 0.000 | 100.000 | 0.000 | 0.000 |
Does anybody know how to leverage CASE statements or another avenue in order to produce this output?
3条答案
按热度按时间pu3pd22g1#
Its can be done this way :
The result is a little bit different that you expected :
Demo here
nwlqm0z12#
I'd suggest to use CTE and PIVOT .
SQL Fiddle
oaxa6hgo3#
There is no need to divide the results of 2 aggregate
COUNT()
s.You can simplify the conditional aggregation with
AVG()
aggregate function:See the demo .