从具有相同结构的多个表中选择 [英] SELECT from multiple tables with the same structure

查看:45
本文介绍了从具有相同结构的多个表中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,如果之前有人问过这个问题,我很抱歉,我在 Google 中找不到任何问题.

Hi and sorry in advance if this question was asked before, i could not find any in Google.

我正在为我的问题寻找解决方案;我有多个结构相同的报告表(数据来自不同的来源,我不得不拆分表格),我需要执行一个 SELECT 语句,该语句将从所有这些表中获取所需的数据,但我也试图从所述表的集体结果中应用 GROUP BY .

I am searching a solution for my issue; I have multiple report tables with the same structure (data is coming from different sources and i had to split the tables), I need to perform a SELECT statement that will fetch the needed data from all of those tables but i am also trying to apply a GROUP BY from the collective result of said tables.

例如:当为每个表的日期应用 GROUP BY 时,它将按日期对任何特定表进行分组,但是当将所有结果合并在一起时,我留下了多个分组表而不是具有必要分组的单个结果.

For example: When applying a GROUP BY for date for each table it will group any specific table by its date, but when merging all of the results together i am left with multiple grouped tables and not a single result with the necessary groupings.

我知道如何为特定表执行 GROUP BY 但我不知道如何在不接触任何复杂的 PHP 脚本的情况下执行它.

I know how to perform a GROUP BY for a specific table but i have no idea how can i perform it without the touch of any complicated PHP scripts.

我没有任何关于我所做的事情的例子,因为到目前为止我想不出任何想法.

I do not have any examples of what i did because i could not think of any ideas so far.

PHP 脚本也可以解决这个问题,但我更喜欢它使用纯 SQL.

A PHP script will do the trick too but i prefer it to be in plain SQL.

谢谢.

推荐答案

通常用 UNION 将多张表合并为 1 组数据,然后可以将整个数据作为 1 组数据:

Combining multiple tables into 1 set of data is usually done with UNION , then you can use the entire data as 1 set of data :

SELECT <Col1>,<Col2>,SUM(<Col3>) as Sum_Col_3
FROM(
    SELECT <Col1>,<Col2>,<Col3> FROM TableA 
    UNION ALL
    SELECT <Col1>,<Col2>,<Col3> FROM TableB
    UNION ALL
    SELECT <Col1>,<Col2>,<Col3> FROM TableC) t
GROUP BY <Col1>,<Col2>

这篇关于从具有相同结构的多个表中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆