【问题标题】:Equivalent to doing a join after the group by相当于在group by之后做一个join
【发布时间】:2015-01-01 13:29:58
【问题描述】:

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

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;

有没有更好的方法来做到这一点?

【问题讨论】:

  • 您当前的解决方案是否适用于 SSMS?
  • @PareshJadhav 是的(SQL server 2014 如果有影响的话)
  • 在合并时,您添加了条件 s1.date = s2.date,这将消除两个表中的行并显示匹配的结果。我会建议你使用两个查询的联合。另外,添加一个硬编码列“S1”和“S2”来标识联合后哪一行属于哪个表。
  • @PareshJadhav 所以我考虑使用联合,但是我会为每个数据获取两行,然后我需要在每个数据中添加一个额外的列,使用组连接进行分组。有没有办法做到这一点?
  • 那么 Thiago 的解决方案很好。

标签: sql-server group-by inner-query


【解决方案1】:

试试这个:

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;

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

【讨论】:

  • 所以这比我的要好得多(大约 50% 的性能提升),但仍然有一个连接。有没有办法摆脱它?
  • 我在不使用联接的情况下添加了第二个查询。看看它是否适合你。
  • 我认为内部查询需要一个 from 子句(很确定这是唯一的错误)
  • 谢谢,这样好多了。
【解决方案2】:

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

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 数据库中的工作 sn-p

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 子句之后使用子查询。

【讨论】:

  • 不知道为什么我以前认为我做不到。谢谢。
猜你喜欢
  • 2019-04-26
  • 2016-01-06
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
  • 2011-10-13
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多