1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[SQL] Joining tables when values are missing

Discussão em 'Outras Linguagens' iniciado por Stack, Outubro 7, 2024 às 08:22.

  1. Stack

    Stack Membro Participativo

    I have the following query to get the names of categories and subcategories for items given by an ID:

    SELECT a.value, b.value FROM X a
    INNER JOIN X b ON a.ID = a.ID
    AND a.NAME = 'Category'
    AND b.NAME = 'Subcategory'


    The issue is that sometimes my categories do not have any subcategories. In that case, there is no row for Subcategory for that ID. Removing b.NAME = 'Subcategory' is not really an option either since there are over fifty distinct values for X.NAME. Do I have any other option than creating an X.NAME = 'Subcategory' with X.value = NULL in cases subcategory is missing?

    So, I want a query which returns the Category and a NULL value when subcategory is missing.

    Here's some sample data:

    insert into X values ('10101', 'Category', 'Murder');
    insert into X values ('10101', 'Subcategory', 'Strangulation');
    insert into X values ('15151', 'Category', 'Theft');
    insert into X values ('15151', 'Subcategory', 'Vehical');
    insert into X values ('15151', 'Severity', 'High');
    insert into X values ('33456', 'Category', 'Theft');
    insert into X values ('45565', 'Category', 'Murder');
    insert into X values ('45565', 'Severity', 'Low');
    insert into X values ('76543', 'Category', 'Violence');
    insert into X values ('76543', 'Subcategory', 'Domestic Violence');
    insert into X values ('76543', 'Severity', 'Medium');

    Continue reading...

Compartilhe esta Página