【发布时间】: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