sql - SQL 查询没有返回正确的结果 - SQLite
问题描述
我有三张桌子:
充电量:
cust_sign_month month months_since_cust country Charge_volume
----------------------------------------------------------------------------------------
2018-01 2018-01 1 DE 100
2018-01 2018-02 1 DE 100
2018-01 2018-03 1 DE 100
2019-01 2019-01 1 IN 100
2019-02 2019-02 1 IN 1,000
2019-03 2019-03 1 IN 1,000
2019-04 2019-04 1 IN 1,000
Active_Customers
:
cust_sign_month month months_since_cust country perc_active_cust
2018-01 2018-01 1 DE 72%
2018-01 2018-02 1 DE 71%
2018-01 2018-03 1 DE 69%
2019-01 2019-01 1 IN 72%
2019-02 2019-02 1 IN 71%
2019-03 2019-03 1 IN 80%
2019-04 2019-04 1 IN 90%
New_customers
:
month country new_cust_onboarded
-----------------------------------------------
2018-01 DE 40,000
2018-02 DE 41,000
2018-03 DE 42,000
2019-01 IN 43,000
2019-02 IN 30,000
2019-03 IN 21,000
2019-04 IN 12,000
JOIN 条件:将分别在 onActive_customers
和month 加入。并且将加入两个表中的所有公共键New_Customers
cust_sign_month
Charge_volume
Active_customers
我的问题是,我需要按从 2019-01 到 2019-04 的月份来获取 2019 年的总收费量。
输出应如下所示:
Activity_Month Total_transactions_2019
---------------------------------------------
2019-01 309600
2019-02 23430000
2019-03 18480000
2019-04 11880000
我已经编写了以下查询,但它没有返回任何结果,并且出现错误
SQL 错误 [1]: [SQLITE_ERROR] SQL 错误或缺少数据库(不明确的列名:月份)
我的查询:
SELECT
a.month AS Activity_Month,
SUM(REPLACE(a.Charge_volume, ',', '') * (REPLACE(c.new_cust_onboarded , ',', '') * b.perc_active_cust) AS Total_transactions_2019
FROM
Charge_volume a
JOIN
Active_Customers b
JOIN
New_customers c ON a.cust_sign_month = b.cust_sign_month
AND a.country = b.country
AND a.month = b.month
AND a.months_since_cust = b.months_since_cust
AND b.cust_sign_month = c.month
AND b.country = c.country
AND substring(a.month, 1, 4) = '2019'
GROUP BY
month
ORDER BY
month
解决方案
这是您正确且有效的 SQL 查询。但是SUM
函数中的表达式并没有给出预期的结果。也许您需要将perc_active_cust
列的值除以 100。
SELECT
a.month AS Activity_Month,
SUM(
REPLACE(a.Charge_volume, ',', '') *
REPLACE(c.new_cust_onboarded , ',', '') * (b.perc_active_cust / 100)
) AS Total_transactions_2019
FROM Charge_volume a
JOIN Active_Customers b
ON a.cust_sign_month = b.cust_sign_month
AND a.country = b.country
AND a.month = b.month
AND a.months_since_cust = b.months_since_cust
JOIN New_customers c
ON b.cust_sign_month = c.month
AND b.country = c.country
WHERE a.month BETWEEN '2019-01' AND '2019-04'
GROUP BY a.month
ORDER BY a.month
请注意,该substring
函数在 SQLite 中不存在。
推荐阅读
- php - 即使该语句为图像标题返回 true,条件语句也不起作用
- java - 数组操作:HackerRank 问题:JAVA
- flutter - 颤振不应该根据设计缩小或放大图像和文本吗?为什么我看到了很大的不同?
- javascript - 如何从作为模块导出的请求中获取回调函数的返回值
- java - Office 365 使用 Java SDK 与图形 API 集成的问题
- java - 如何在 Spring MVC 中记录传入请求
- c# - 为什么即使返回值也不会在浏览器中显示 viewbag 值?
- sql - 使用另一个表中的标识符更新表中的值 (SQL)
- flutter - Flutter 中 PageView 的默认曲线行为是什么?
- c# - 如何在运行时创建结构并将 byte[] 指针转换为创建的结构?