繁体   English   中英

SQL - 如何将来自同一个表的两个查询合并到一个表中,每个查询都有单独的列?

[英]SQL - How to combine two queries from the same tables into one table with separate columns from each query?

我在数据库中有一个表,其结构如下:

| date      | app    | action    | response |
|-----------|--------|-----------|----------|
| 9/22/2022 | e-file | launch    | 2        |
| 9/22/2022 | e-file | login     | 3        |
| 9/22/2022 | e-file | edit      | 5        |
| 9/22/2022 | e-file | clicksave | 6        |
| 9/22/2022 | e-file | logout    | 7        |
| 9/28/2022 | cube   | launch    | 3        |
| 9/28/2022 | cube   | login     | 2        |
| 9/28/2022 | cube   | edit      | 7        |
| 9/28/2022 | cube   | clicksave | 8        |
| 9/28/2022 | cube   | logout    | 9        |

我想实现这个结果以便在 grafana 表中使用它:

| action    | response_e-file | response_cube | e vs cube |
|-----------|-----------------|---------------|-----------|
| launch    | 2               | 3             | 0.33      |
| login     | 3               | 2             | -0.33     |
| edit      | 5               | 7             | 0.40      |
| clicksave | 6               | 8             | 0.33      |
| logout    | 7               | 9             | 0.29      |

响应列将根据 app 列中的值拆分为不同的列。 此外,将有一个新列基于两个响应列执行简单的数学运算。

我是 SQL 的新手,运气不佳。

实现这一目标的查询是什么? 这甚至可以实现吗?

我们pivot使用case-when然后group by action分组。

select   action
        ,max(case app when 'e-file' then response end)                                                                                             as "response_e-file"              
        ,max(case app when 'cube'   then response end)                                                                                             as "response_cube"   
        ,(max(case app when 'cube' then response end)-max(case app when 'e-file' then response end))/max(case app when 'e-file' then response end) as "e vs cube"
from     t
group by action
行动 response_e-文件 响应立方体 电子对立方体
发射 2个 3个 0.5000
登录 3个 2个 -0.3333
编辑 5个 7 0.4000
点击保存 6个 8个 0.3333
登出 7 9 0.2857

小提琴

您可以通过使用嵌套查询并调整以下查询以适合您的用例来实现此目的 -

SELECT action, [response_e-file], [response_cube], (response_cube - response_e-file) / response_cube as e_vs_cube FROM (
    SELECT action, col, val FROM (
        SELECT *, 'response_'+app as col, response as val FROM @T
    ) t
) tt

由于值似乎不一致,因此不清楚如何计算e_vs_cube列。

对于前两行,它看起来像 (response_cube (response_cube - response_e-file) / response_cube但其他的看起来像(response_cube - response_e-file) / response_e-file

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM