填充MySQL SELECT语句中缺少的数据

fd3cxomn  于 2022-12-17  发布在  Mysql
关注(0)|答案(3)|浏览(141)

我想展示来自MySQL数据库(实际上是MariaDB)的信息,大致如下所示:

SELECT Client, Year, SUM(Sales) 
FROM MySalesTable 
GROUP BY Client, Year 
ORDER BY Client, Year DESC

问题是,如果客户端没有特定年份的数据,MySQL会完全跳过这些行,而我希望表包含某个范围内的所有年份(例如:2015-2022)-用零、空值或空字符串填充。
通常,我会用left-JOIN查询一个包含年份的表(或者从一个包含任何类型的日历信息的表中过滤年份),但是我手头没有它。我知道我可以创建一个TEMPORARY表并相应地填充它-但是有没有可能创建一个临时的'伪表'作为子查询呢?在伪代码中类似于:
SELECT ... FROM (SELECT Year FROM [2015, 2016,...2022]) LEFT JOIN ....
先谢谢你。

guz6ccqo

guz6ccqo1#

一个选项是在以下范围内使用LEFT JOIN

  • 每一位客户与每年
  • 您的查询

然后对缺失的Sales应用COALESCE函数。

WITH combinations AS (
    SELECT clients.Client, years.Year
    FROM       (SELECT DISTINCT Client FROM MySalesTable) clients
    INNER JOIN (SELECT DISTINCT Year FROM MySalesTable) years ON 1=1
) 
SELECT Client,
       Year,
       COALESCE(total_sales, 0) AS total_sales
FROM      combinations
LEFT JOIN (SELECT Client, Year, SUM(Sales) AS total_sales
           FROM MySalesTable 
           GROUP BY Client, Year) sales
       ON combinations.Client = sales.Client 
      AND combinations.Year = sales.Year
ORDER BY Client, Year DESC
xxslljrj

xxslljrj2#

最明显的解决方案(尽管效率很低)是从同一个表中获取一个由年份组成的列表。

SELECT a.client, allyears.year, sum(a.sales) 
FROM mysalestable
FROM (SELECT DISTINCT year FROM MySalesTable) allyears 
LEFT JOIN MySalesTable a
ON allyears.year=a.year
....

然而,这仍然不会列出一年中没有销售额的客户--实际上,您需要一个数据源来生成所有年份和所有客户的列表--这需要一个笛卡尔连接......

SELECT allclients.client, allyears.year, sum(a.sales) 
FROM (SELECT DISTINCT year FROM MySalesTable) allyears
JOIN (SELECT DISTINCT client FROM MySalesTable) allclients 
LEFT JOIN MySalesTable a
ON allyears.year=a.year
AND allclients.client=a.client
GROUP BY allclients.client, allyears.year
ORDER BY allclients.client, allyears.year DESC

(You可能有其他表,查询所有年份和所有客户端的成本较低)
不幸的是,MySQL没有实现row generator的机制。

9gm1akwq

9gm1akwq3#

我想这对你会有帮助:
How to SELECT based on value of another SELECT

select t1.*, t2.* from (
SELECT Client, Year, SUM(Sales) FROM MySalesTable GROUP BY Client, Year
) as t1,
(
SELECT Client, Year, SUM(Sales) FROM MySalesTable GROUP BY Client, Year
) as t2
where t1.Client = t2.Client

甚至可以内部连接表

相关问题