Free cookie consent management tool by TermsFeed Policy Generator
  • Azure SQL
  •    5 page views
  •   0 video views
  • 2024, September 24, Tuesday

#056 Combine queries by union in Azure SQL

Como combinar consultas por união em Consulta (SELECT) existente na linguagem de Manipulação de Dados (DML) do Azure SQL/SQL Server

This T-SQL code uses the UNION clause to combine the results of two different queries, one for the table [f].[ Mercado_Exportacao] and another for table [f]. [Mercado_Importacao]. I'll explain each part of the code

:
  1. Union Part One:

    SELECT [CO_ANO], [
    CO_MES], [KG_LIQUIDO], 'Export' AS TYPE
    FROM [f]. [Mercado_Exportacao]
    
    • SELECT: Indicates that the next part of the code will specify which columns will be returned in the query.
    • [CO_ANO], [CO_MES
    • ], [KG_LIQUIDO]: Select the "CO_ANO", "CO_MES", and "KG_LIQUIDO" columns.
    • AS TYPE '
    • Export': Adds an additional column called 'TYPE' with the constant 'Export' value for each resulting row in the table [f]. [Mercado_Exportacao].
  2. UNION:
  3. UNION Operator

    • : Combines the results of two queries, eliminating duplicates. UNION requires queries to have the same number of columns, with matching data types.
  4. Union Part Two:

    SELECT [CO_ANO], [
    CO_MES], [KG_LIQUIDO], 'Import' AS TYPE
    FROM [f]. [Mercado_Importacao]
    
    • SELECT: Indicates that the next part of the code will specify which columns will be returned in the query.
    • [CO_ANO], [CO_MES
    • ], [KG_LIQUIDO]: Select the "CO_ANO", "CO_MES", and "KG_LIQUIDO" columns.
    • AS TYPE '
    • Import': Adds an additional column called 'TYPE' with the constant 'Import' value for each resulting row of the table [f]. [Mercado_Importacao].

The final result of the query is the combination of the results of the two parts, where each row will have the columns "CO_ANO", "CO_MES", "KG_LIQUIDO" and "TYPE". The "TYPE" column indicates whether the data is export-related or import-related. This is useful when you need to group or analyze data from different related tables.

This content contains
  • Content Imagem
  • Language Portuguese
  • Duration
  • Subtitles Não

  • Reading time 1 min 27 seg

avatar
Fabio Santos

Data Scientist and Consultant for Digital and Analytics Solutions


  • Share

Youtube Channel

@fabioms

Subscribe now