[英]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.