Add column to SQL query results

前端 未结 2 682
故里飘歌
故里飘歌 2021-02-12 20:17

I\'m putting together a report in SSRS. The dataset is populated with a SQL query of an MS SQL server. It\'s querying several similar tables using Union All. The problem is that

相关标签:
2条回答
  • 2021-02-12 20:37

    Manually add it when you build the query:

    SELECT 'Site1' AS SiteName, t1.column, t1.column2
    FROM t1
    
    UNION ALL
    SELECT 'Site2' AS SiteName, t2.column, t2.column2
    FROM t2
    
    UNION ALL
    ...
    

    EXAMPLE:

    DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
    DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))
    
    INSERT INTO @t1
    SELECT 1, 'a'
    UNION SELECT 2, 'b'
    
    INSERT INTO @t2
    SELECT 3, 'c'
    UNION SELECT 4, 'd'
    
    
    SELECT 'Site1' AS SiteName, t1.column1, t1.column2
    FROM @t1 t1
    
    UNION ALL
    SELECT 'Site2' AS SiteName, t2.column1, t2.column2
    FROM @t2 t2
    

    RESULT:

    SiteName  column1  column2
    Site1       1      a
    Site1       2      b
    Site2       3      c
    Site2       4      d
    
    0 讨论(0)
  • 2021-02-12 20:41

    why dont you add a "source" column to each of the queries with a static value like

    select 'source 1' as Source, column1, column2...
    from table1
    
    UNION ALL
    
    select 'source 2' as Source, column1, column2...
    from table2
    
    0 讨论(0)
提交回复
热议问题