I am junior web developer. I am studying about postgres, and I have a question about use case of case statement.
This query finds several rows with data that most closely matches a particular word.
The result can be multiple.
In this query, the ranking value is calculated using a case statement according to the similarity for each row.
It is understood that the case statement returns a value that matches each execution.
When the case statement is used inside the min and window functions, I wonder how to find the result.
the given table PostalCode is..
|---------------------|------------------|
| pcode | name |
|---------------------|------------------|
| 100456 | a |
|---------------------|------------------|
| 111343 | b |
|---------------------|------------------|
| 101334 | c |
|---------------------|------------------|
| 100567 | d |
|---------------------|------------------|
| 102234 | e |
|---------------------|------------------|
The query is..
SELECT pcode,
name
FROM (SELECT pcode,
name,
CASE WHEN pcode = '100123' THEN 0
WHEN pcode = '10012%' THEN 1
WHEN pcode = '1001%' THEN 2
WHEN pcode = '100%' THEN 3
WHEN pcode = '10%' THEN 4
WHEN pcode = '1%' THEN 5
ELSE NULL END AS hit_code,
MIN(CASE WHEN pcode = '100123' THEN 0
WHEN pcode = '10012%' THEN 1
WHEN pcode = '1001%' THEN 2
WHEN pcode = '100%' THEN 3
WHEN pcode = '10%' THEN 4
WHEN pcode = '1%' THEN 5
ELSE NULL END)
OVER(ORDER BY CASE WHEN pcode = '100123' THEN 0
WHEN pcode = '10012%' THEN 1
WHEN pcode = '1001%' THEN 2
WHEN pcode = '100%' THEN 3
WHEN pcode = '10%' THEN 4
WHEN pcode = '1%' THEN 5
ELSE NULL END) AS min_code,
FROM PostalCODE) Foo
WHERE hit_code = min_code;
and the result will be
|---------------------|------------------|
| pcode | name |
|---------------------|------------------|
| 100456 | a |
|---------------------|------------------|
| 100567 | d |
|---------------------|------------------|
I know that the first case statement returns different values depending on the similarity.
After case end, the MIN function is called, but what will it return?
I can not understand this context.
Please help me.
If you help me, I can't give you anything, but I would like to express my sincere gratitude.
Thanks for reading.