我有一个查询可以提供正确的信息,但我无法弄清楚如何获得不同的日子并总结计数。下面是我的查询,结果显示我得到了什么,以及我想回来的内容。我以为工会会加入他们并给我我想要的结果。我已经搜索了很长时间,并没有找到任何关于这个主题的帮助。任何帮助将不胜感激。提前谢谢。
SELECT COUNT(log_datetime) AS icount, CONVERT(varchar, log_datetime, 101) AS logdate
from openrowset('sqloledb', 'ServerName1';'UserID';'Password',
'select * from DatabaseName..TableName where field1 > 899')
group by convert(varchar, log_datetime, 101)
union
SELECT COUNT(log_datetime) AS icount, CONVERT(varchar, log_datetime, 101) AS logdate
from openrowset('sqloledb', 'ServerName2';'UserID';'Password',
'select * from DatabaseName..TableName where field1 > 899')
group by convert(varchar, log_datetime, 101)
order by logdate
Results
235 01/10/2013
312 01/10/2013
3091 01/11/2013
3197 01/11/2013
3339 01/12/2013
3536 01/12/2013
Wanted Results
547 01/10/2013
6288 01/11/2013
6875 01/12/2013
答案 0 :(得分:1)
你可以试试这个
SELECT SUM(icount) AS icount, logdate FROM
(
SELECT COUNT(log_datetime) AS icount, CONVERT(varchar, log_datetime, 101) AS logdate
FROM openrowset('sqloledb', 'ServerName1';'UserID';'Password',
'select * from DatabaseName..TableName where field1 > 899')
GROUP BY convert(varchar, log_datetime, 101)
UNION ALL
SELECT COUNT(log_datetime) AS icount, CONVERT(varchar, log_datetime, 101) AS logdate
FROM openrowset('sqloledb', 'ServerName2';'UserID';'Password',
'select * from DatabaseName..TableName where field1 > 899')
GROUP BY convert(varchar, log_datetime, 101)
) AS tbl
GROUP BY logdate
ORDER BY logdate
答案 1 :(得分:1)
SELECT count(1) icount, AA.logdate FROM
(
SELECT CONVERT(varchar, log_datetime, 101) AS logdate
from openrowset('sqloledb', 'ServerName1';'UserID';'Password',
'select * from DatabaseName..TableName where field1 > 899')
union all
SELECT CONVERT(varchar, log_datetime, 101) AS logdate
from openrowset('sqloledb', 'ServerName2';'UserID';'Password',
'select * from DatabaseName..TableName where field1 > 899')
) AA
group by AA.logdate order by AA.logdate
答案 2 :(得分:0)
我相信peterm的答案是正确的,只是想添加一个关于原因的说明。
使用SQL,你必须在集合中思考。您正在创建两个唯一的数据集,并使用UNION将它们组合在一起。但是,GROUP BY语句在每个集合中,而不是组合。因此,多行结果。通过使用另一个SELECT语句包装所有内容,您将查询组合集,现在可以进行分组和聚合。