SQL UNION在2个表变量上,其中日期相同但其他数据不相同

时间:2010-10-25 15:43:48

标签: sql sql-server sql-server-2005 tsql

我有2个表变量@Data和@DateTable

@Data包含以下内容:

Company   Date        Type      Select
Altec    12-1-2010     d           2
Altec    12-1-2010     a           2
Alect   12-3-2010     d            3

@DateTable包含以下内容:

Company Date          Type Select
Altec    12-1-2010     a    0
Altec    12-3-2010     a    0
Altec    12-5-2010     a    0
Altec    12-6-2010     a    0

我需要在同一个查询中同时显示d和a。因此,如果没有与@data表中的a匹配的d,则需要从@DateTable中提取它。

基本上我想要的结果是

Company DATE      Type Select
ALTEC   12-1-10     d    2
ALTEC   12-1-10     a    2
ALTEC   12-3-10     d    3
ALTEC   12-3-10     a    0 (This is pulled from @DateTable)

如何在不获取@Data表中已有的表的情况下联合这两个表,但也不会从@DateType表中找不到匹配的额外的表.....

3 个答案:

答案 0 :(得分:2)

这是我的看法:

SELECT dt.company,
       dt.date,
       COALESCE(d.type, dt.type) AS type,
       COALESCE(d.select, dt.select) AS select
FROM @DateTable dt 
     LEFT JOIN @Data d ON d.company = dt.company
                       AND d.date = dt.date

答案 1 :(得分:1)

使用EXISTS / NOT EXISTS:

 SELECT Company, Date, Type, Select FROM DataTable
 UNION ALL
 SELECT Company, Date, Type, Select FROM DateTable
    WHERE EXISTS (SELECT * FROM DataTable WHERE Company = DateTable.Company AND Date = DateTable.Date)
    AND NOT EXISTS (SELECT * FROM DataTable WHERE Company = DateTable.Company AND Date = DateTable.Date AND Type = DateTable.Type)

答案 2 :(得分:0)

使用Union:

select [Company], [Date], [Type], sum([Select]) as [Select]
from (select [Company], [Date], [Type], [Select] from @Data union all
      select [Company], [Date], [Type], [Select] from @DateTable) sq
group by [Company], [Date], [Type]