简体   繁体   English

查询 - 计算具有相同列的 2 个数据库表之间的差异

[英]Query - Calculate the difference between 2 DB tables with the same columns

How do you calculate the difference between 2 DB tables with the same columns using query?如何使用查询计算具有相同列的 2 个数据库表之间的差异? They both have Columns as 'app', 'installs', 'usage'.他们都有“应用”、“安装”、“使用”等列。 Thanks in advance.提前致谢。

My notworking query我不工作的查询

WITH apps AS (
SELECT app, installs_curr, usage_curr FROM (
    SELECT app, installs AS installs_curr, usage AS usage_curr
    FROM e5a.apps_2020_07
    )
SELECT app, installs_prev, usage_prev FROM (
   SELECT app, installs AS installs_prev, usage AS usage_prev
    FROM e5a.apps_2020_06
    )
)
SELECT app, installs_curr – installs_prev AS installs_delta, usage_curr – usage_prev AS usage_delta FROM apps
ORDER BY usage_delta DESC
**TABLE e5a.apps_2020_07**

app   installs usage 
snap  20       10

**TABLE e5a.apps_2020_06**

app   installs usage 
snap  12       8
  
**Result through calculation**

app   installs usage 
snap  8       2

It depends on how you want to treat values in one table but not the other.这取决于您希望如何处理一个表中的值而不是另一个表中的值。 A good place to start is with join :一个好的起点是join

SELECT a7.app,
       (a7.installs - a6.installs) AS installs_diff,
       (a7.usage - a6.usage) AS usage_diff
FROM e5a.apps_2020_07 a7 JOIN
     e5a.apps_2020_08 a6
     ON a7.apps = a6.apps;

This include only apps that are in both tables.这仅包括两个表中的应用程序。

You should fix your data model so you have only one table with the month as a column in the table.您应该修复数据 model,这样您只有一个表,其中月份作为表中的一列。

Assuming that App is primary key, then you can simply subtract:假设 App 是主键,那么你可以简单地减去:

SELECT a.app, a.installs - b.installs installs_curr, a.usage - b.usage  AS usage_curr
    FROM e5a.apps_2020_07 a inner join e5a.apps_2020_06 b on (a.app = b.app) 

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

相关问题 如何计算db2中两个日期列之间的天数? 如何更正此查询中的天数差异? - How to calculate days between two date columns in db2?? how do i correct the difference of days in this query? SQL查询:要计算两个不同表中的列之间的差异? - SQL Query: Looking to calculate difference between two columns both in different tables? 有没有一种方法可以计算DB2中不同列和行之间的值差 - Is there a way to calculate the difference of values between different columns and rows in DB2 如何计算不同表中两个时间列之间的差异? - How to calculate difference between 2 time columns in distinct tables? 如何使用单个查询计算2个不同表中2个字段之间的差异? - how to calculate difference between 2 fields in 2 different tables using a single query? 计算2个表之间的值差 - Calculate difference in values between 2 tables 如何从不同的表中查询两列序列之间的差异 - How to query for the difference between the sequences of two columns, from differing tables 具有相同结构的表之间的差异 - Difference between tables with the same structure 表中权限查询的区别 - Difference between query of privileges in tables 计算不同行和列中的值之间的差异 - Calculate the difference between the value in different rows and columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM