怎么聚合?

时间:2014-11-12 23:45:57

标签: sql-server aggregate

我有一个CTE中两个临时表连接的结果 - 连接有以下字段:ID, year, flag1, flag2 我将其称为Table1

ID   year flag1 flag2
1    2000  1     0
2    2001  0     1
3    2005  1     0
4    NULL  NULL  NULL
5    NULL  NULL  NULL

在表2中,我有以下数据

4    2006  0     1
5    2007  0     1

如何汇总两个表格?并从表2中显示ID为1,2,3的记录和ID为4,5的记录?

如何在两个表之间聚合数据?并显示结果如下?

ID   year flag1 flag2
1    2000  1     0
2    2001  0     1
3    2005  1     0
4    2006  0     1
5    2007  0     1

2 个答案:

答案 0 :(得分:0)

您可以加入ID并使用coalesce()或isnull()来获取ID 4&的正确(非空)值。 5:

SELECT 
  t1.ID, 
  coalesce(t1.[year], t2.[year]) as [year], 
  coalesce(t1.flag1, t2.flag1) as flag1, 
  coalesce(t1.flag2, t2.flag2) as flag2 
FROM TABLE1 t1
INNER JOIN TABLE2 t2 ON t1.ID = t2.ID

coalesce()(和isnull())将返回其参数的第一个非null值。

如果Table1和Table2具有匹配的ID,但是对于其他字段具有非空值,这可能会给出不正确的结果......但是对于您的示例,它可以正常工作。

答案 1 :(得分:0)

declare @t table (Id int,years int,flag int,flag1 int)
insert into @t (Id,years,flag,flag1)values (1,2000,1,0),
(2,2001,0,1),(3,2005,1,0),(NULL,NULL,NULL,null),(NULL,NULL,NULL,null)

declare @tT table (Id int,years int,flag int,flag1 int)
insert into @tT (Id,years,flag,flag1)values (4,2006,0,1),
(5,2007,0,1)

SELECT T.Id,T.years,T.flag,T.flag1 FROM @t T 
WHERE  T.Id is not null and T.years is not null and T.flag is not null and T.flag1 is not null 
union 
SELECT T.Id,T.years,T.flag,T.flag1 FROM @tT T
WHERE  T.Id is not null and T.years is not null and T.flag is not null and T.flag1 is not null