1

我希望将以下两个查询合并为一个:

select top 100 date, count(*) from sections
where content not like '%some condition%'
group by date
order by date;

select top 100 date, count(*) from sections
group by date
order by date;

就像这个问题,LEFT JOIN after GROUP BY? 除了我需要它适用于 MS SQL Server,而不是 MySQL(不同之处在于 MSSQL 不允许在 from 子句中使用子查询)。

我正在寻找一种方法让结果集包含三列,date第一列count(*)和第二列count(*)

我目前的解决方案是:

select top 100 date, 
(select count(*) from sections s1
where content not like '%some condition%' 
and s1.date = s2.date),
(select count(*) from sections s1
where s1.date=s2.date) from sections as s2
group by date
order by date;

有一个更好的方法吗?

4

2 回答 2

2

尝试这个:

with q1 as (select top 100 date, count(*) total from sections
            where content not like '%some condition%'
            group by date),
q2 as (select top 100 date, count(*) total from sections
       group by date)
select q1.date, q1.total total1, q2.total total2
  from q1
  join q2 on q1.date = q2.date
  order by q1.date

更新:

或这个:

select date,
       count(*) total,
       sum(has_condition) total_condition
from (select top 100 
             date, 
             case when content not like '%some condition%' then 1
                  else 0 end has_condition
        from sections ) t
group by date
order by date;

我没有做任何triout,但这是我的想法。

于 2014-11-05T11:23:07.073 回答
1

这是只需一次选择即可完成工作的查询:

select top 100 date, 
count(*) as count_all,
sum (
  case 
    when content not like '%some condition%' then 1
    else 0
  end
) as count_condition
from sections
group by date
order by date

我还粘贴了 AdventureWorks2012 数据库中的工作片段

select top 100 
ModifiedDate, 
count(*) as count_all,
sum (
case when CarrierTrackingNumber not like '4911%' then 1
else 0
end
) as count_condition
from [Sales].[SalesOrderDetail]
group by ModifiedDate
order by ModifiedDate

供您参考,您可以在 SQL Server 中的 FROM 子句之后使用子查询。

于 2014-11-05T11:37:42.547 回答