1

我有一个查询可以返回正确的信息,但我无法弄清楚如何获得不同的日期并将计数相加。下面是我的查询,结果显示了我得到了什么,以及我希望得到什么。我以为工会会加入他们,并给我想要的结果。我已经搜索了很长时间,但没有找到关于这个主题的任何帮助。任何帮助将不胜感激。先感谢您。

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
4

3 回答 3

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

这是sqlfiddle

于 2013-02-09T01:07:26.813 回答
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
于 2013-02-09T04:56:07.290 回答
0

我相信彼得姆的回答是正确的,只是想添加一个关于原因的注释。

使用 SQL,您必须分组思考。您正在创建两组独特的数据,并使用 UNION 将它们组合起来。但是,您的 GROUP BY 语句在每个集合中,而不是组合中。因此,多行结果。通过使用另一个 SELECT 语句包装所有内容,您正在查询组合集,并且现在可以进行分组和聚合。

于 2013-02-09T02:07:45.270 回答