SQL Double Conditional SELECT without repeating values within a column

Viewed 75

Given a table Details:

Lanugage IsDefault PropertyName
en False Property 119
es True Property 119
fr False Property 119
en False Property 14
es True Property 14
en False Property 16
es True Property 16

I am trying to SELECT * FROM Details WHERE [Language] = 'fr', then SELECT * FROM Details WHERE [Language] != 'fr' AND IsDefault = 1 without repeating PropertyName in the results if it was already selected in SELECT * FROM Details WHERE [Language] = 'fr'.

Expected Result is:

Lanugage IsDefault PropertyName
fr False Property 119
es True Property 14
es True Property 16

However I have tried many things (UNION, NOT EXISTS ...) are the result for me is always:

Lanugage IsDefault PropertyName
fr False Property 119
es True Property 119
es True Property 14
es True Property 16

How would one achieve this?

3 Answers

I would use ROW_NUMBER here:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY PropertyName
                                 ORDER BY CASE LANGUAGE WHEN 'fr' THEN 1 ELSE 2 END) rn
    FROM Details
    WHERE Language = 'fr' OR IsDefault = 1
)

SELECT Language, IsDefault, PropertyName
FROM cte
WHERE rn = 1;

screen capture from demo link below

Demo

The logic above is to use a single query to generate a result set with all candidate records. We also turn out a row number, per property, based on an ordering where French properties always rank higher (read: row number is lower) than properties from all other countries. We retain only one record per property.

You can go for UNION ALL also to achieve the result.

;cte_fr AS
(SELECT PropertyName, IsDefault, Language
FROM Details
WHERE Language = 'Fr')
select propertyname, isdefault,language from cte_fr
UNION ALL
select propertyname, isdefault,language from Details as d
WHERE NOT EXISTS (
select * from CTE_FR
WHERE PropertyName = d.PropertyName
)
and d.IsDefault = 1;
propertyname isdefault language
Property 119 0 fr
Property 14 1 es
Property 16 1 es

You can get your desired results simply by grouping,

select  Max([Language]), Max(IsDefault), Max(PropertyName)
from Details
where [language]='fr' or ([language] !='fr' and isdefault='True')
group by PropertyName
Related