sql-server - 我如何加入 2 个查询以显示在 1 个表中
问题描述
我有 2 个查询,它们几乎相同,它们返回相同数量的列。
我想创建一个存储过程来获取基于 2 个日期和 1 个参数的 1 个表。
select
Datepart(minute, created_at) as minuto,
avg(salida_1) as 'salida_1'
from
salida_a
where
created_at between '27/01/2020 04:00:00' and '27/01/2020 05:00:00'
and id_linea = 6
group by
datepart(minute, created_at)
order by
minuto
select
Datepart(minute, created_at) as minuto,
avg(entrada_1) as 'entrada_1'
from
entrada_a
where
created_at between '27/01/2020 04:00:00' and'27/01/2020 05:00:00'
and id_linea = 6
group by
datepart(minute, created_at)
order by
minuto
每个查询返回
"minuto0","entrada_1"
其他查询
"minuto1","salida_1"
我想要一张这样的桌子
"minuto0","entrada_1","minuto1","salida_1"
或这个
"minuto0","entrada_1","salida_1"
帮助
解决方案
作为我的联合/条件 agg 的替代方案,您可以使用联接。这对您来说可能更容易理解:
获取您现有的查询并将它们转换为 cte:
WITH s as (
select Datepart(minute, created_at) as minuto, avg(salida_1) as 'salida_1' from salida_a where created_at between '27/01/2020 04:00:00' and '27/01/2020 05:00:00' and id_linea = 6 group by datepart(minute, created_at)
),
E as (
select Datepart(minute, created_at) as minuto, avg(entrada_1) as 'entrada_1' from entrada_a where created_at between '27/01/2020 04:00:00' and'27/01/2020 05:00:00' and id_linea = 6 group by datepart(minute, created_at)
)
SELECT
COALESCE(e.minuto, s.minuto) as minuto,
S.salida_1,
E.entrada_1
FROM
s FULL OUTER JOIN e ON s.minuto = e.minuto
ORDER BY minuto
它接受您的两个查询并将它们连接起来,使它们在一行上,它使用 s 或 e 中的 minuto,然后使用每个表中的值。如果 s 中的 minuto 为 1,而表 e 的 minuto 不为 1,则 e 的 avg 将为空。如果您希望它改为 0,请再次使用 coalesce 来给出 0 而不是 null:
COALESCE(e.entrada_1, 0)
推荐阅读
- ios - 在 Array.contains 方法中访问当前对象
- sql - 为我的用户在 SO 上获得徽章的“等级” - 查询速度很慢 - 可以加速吗?
- c# - 如何使用 Microsoft Fakes 填充扩展方法?
- azure - 在 Microsoft Bot Framework V4 Nodejs 中屏蔽用户输入的密码
- javascript - 如果我在 Express Gateway 应用程序中记录 http 响应,它不会显示响应数据
- powershell - 将 Powershell 对象导出到 CSV - 拒绝访问
- sql - SQLCMD , 'tee' 不被识别为内部或外部命令
- mongodb - 如何在字符串数组中搜索字符串
- spring-mvc - 我的 spring-mvc 应用程序在 glassfish 4.1 服务器上抛出 'BeanCreationException: Error Creating bean...'requestMappingHandlerAdapter'..'
- javascript - 控制内容位于通过对象标记插入主站点 (index.html) 的外部 html 文件中