GROUP BY - add result with null group by key to other result

时间:2016-05-11 11:35:28

标签: sql sql-server-2008 tsql

Title sucks, I couldn't come up with a good one explaining what I want, sorry.

I have a complex query which I have simplified to one below. Basically it always must return one record. Main table has a left join (it can't be an inner join) with another table from which it retrieves count of records it matches and so far it also returned one record, but now there is case where one property from secondary table can be null and if so, that record must also be included, but then it returns two rows. I somehow need to make them as one record where both matching records count and results that contain that null value count are summed.

So, given these tables:

   TableA         TableB
+----+------+  +----+------+
| id | type |  | id | type |
+----+------+  +----+------+
|  1 |Email |  |  1 |Email |
|  2 |Twitt |  |  2 |null  |
+----+------+  +----+------+

And this query:

select * from TableA a
left join 
  (select count(distinct b.id) count, b.type
  from TableB b
  Group by b.type) as asd
  on a.type = asd.type or asd.type is null
where a.type = 'Email'

which returns:

+----+------+-------+------+
| id | type | count | type |
+----+------+-------+------+
|  1 |Email |   1   |(null)|
|  1 |Email |   1   |Email |
+----+------+-------+------+

is it possible to return it like this:?

+----+------+-------+------+
| id | type | count | type |
+----+------+-------+------+
|  1 |Email |   2   |Email |
+----+------+-------+------+

I actually don't even need to returns secondary's table's type just the right count. Here is a fiddle I made: http://sqlfiddle.com/#!3/8cf5c/2

3 个答案:

答案 0 :(得分:1)

应该是这个

select a.Type, count(*) from TableA a
left join 
  (select count(distinct b.id) count, b.type
  from TableB b
  Group by b.type) as asd
  on a.type = asd.type or asd.type is null
where a.type = 'Email'
group by a.type

答案 1 :(得分:1)

我不知道为什么你需要最后的类型,如果你可以删除它,查询就像这样

select a.id, a.type, count(asd.count) as count
from TableA a join 
     (select count(distinct b.id) as count, b.type
      from TableB b
      Group by b.type
     ) asd
     on a.type = asd.type OR asd.type IS NULL
where a.type = 'Email'
group by a.id, a.type

但是如果你想要完全相同的结果,我想你可以尝试这个查询

select a.id, a.type, count(asd.count) as count, ISNULL(asd.type,a.type) as type
from TableA a join 
     (select count(distinct b.id) as count, b.type
      from TableB b
      Group by b.type
     ) asd
     on a.type = asd.type OR asd.type IS NULL
where a.type = 'Email'
group by a.id, a.type, ISNULL(asd.type,a.type)

答案 2 :(得分:0)

以下查询可能会为您提供所需的输出: -

选择id,type,count(*)Count from( 从TableA中选择* UNION ALL 从TableB中选择* ) 一个 按ID分组,输入

输出: -

id  type    Count
1   Email   2
2   NULL    1