加入2个mssql查询


0

我需要加入MSSQL查询,但我没有得到任何关于这一点。

两个查询都返回一个值:

 SELECT COUNT(*) FROM sysjobhistory WHERE run_status <> 1 AND step_id = 0;

 SELECT MAX (run_date) FROM sysjobhistory WHERE run_status = 1 AND step_id = 0;

我是一个完整的SQL菜鸟所以任何帮助表示赞赏


您是否希望在sysjobhistory表的单个查询中返回两个值?
Milica Medic 2014年

Answers:


1

很难说出你想要的输出是什么,但我认为这会对你有所帮助:

DECLARE @Count INT
DECLARE @MaxRunDate DateTime -- I'm guessing run_date is a datetime... 

SELECT @Count = COUNT(*)
    FROM sysjobhistory WHERE run_status <> 1 AND step_id = 0;
SELECT @MaxRunDate = MAX(run_date)
    FROM sysjobhistory WHERE run_status = 1 AND step_id = 0;

SELECT @Count, @MaxRunDate

还有其他方法可以做到这一点,包括使用JOIN,但我相信上面的内容更容易理解,特别是初学者。


谢谢,这样做。我只需要从一个查询中返回两个值。这是一个nagios插件,需要两个值来执行检查
Bruno9779 2014年

2

如果要联合,请为列命名:

SELECT COUNT(*) AS 'Column' FROM sysjobhistory WHERE run_status <> 1 AND step_id = 0
 UNION
SELECT MAX (run_date) AS 'Column' FROM sysjobhistory WHERE run_status = 1 AND step_id = 0

如果您想在同一查询中使用两列,则可以使用子查询:

SELECT (SELECT COUNT(*) FROM sysjobhistory WHERE run_status <> 1 AND step_id = 0) AS 'Count', (SELECT MAX (run_date) AS 'Column' FROM sysjobhistory WHERE run_status = 1 AND step_id = 0) AS 'Max'
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.