mysql连接查询

发布于 2024-08-12 07:18:28 字数 511 浏览 2 评论 0原文

我有一个包含下表的查询(简化为仅显示感兴趣的列)。

t1
code

t2
code, period, status

t3
period, desc

现在我所拥有的是,

t3 是一个独特的“周期”表。

t1 是唯一代码表。

t2 是将两者链接在一起的连接表以及状态,在本示例中状态=(A,B,C)。

我正在做的是创建一个按“期间”分组的查询结果,并具有每个状态中的“代码”计数。

这很容易解决,但我想将其扩展到,不仅要计算 A、B 和 C 中的“代码”计数,还要计算与句点不相关的代码计数,或者换句话说,给定时间段内不在 t2 中的代码计数。

所以我正在寻找的结果是

Period    A    B    C   (Codes from t1 not found in t2)
P1        10   5    2   3
P2        5    5    5   10

I have a query with the following tables (reduced to show only the interested columns).

t1
code

t2
code, period, status

t3
period, desc

Now what I have is,

t3 is a table of unique "periods".

t1 is a table of unique codes.

t2 is the join table linking both together, along with a status, for sake of this example status=(A,B,C).

What I'm doing is create a query result that is grouped by "period" and has the count of 'codes' in each status.

That is easy to solve, but want I want to extend this to, is to have not only a count of 'code's in A, B and C but also a count of the codes that AREN'T associated with a period or in other words, a count of the codes that aren't in t2 for a given period.

So the result i'm looking for is

Period    A    B    C   (Codes from t1 not found in t2)
P1        10   5    2   3
P2        5    5    5   10

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无法回应 2024-08-19 07:18:28

您可以使用交叉连接来选择所有期间的所有代码的矩阵。这允许您计算不存在的行:

select
    sum(case when t2.status is 'A' then 1 else 0 end) as ACount,
    sum(case when t2.status is 'B' then 1 else 0 end) as BCount,
    ...
    sum(case when t2.code is null then 1 else 0 end) as NotPresentCount
from       t1
cross join t3
left join  t2 
on         t2.code = t1.code and t2.period = t3.period
group by   t3.period

You can use cross join to select a matrix of all codes for all periods. That allows you to count the rows which are not present:

select
    sum(case when t2.status is 'A' then 1 else 0 end) as ACount,
    sum(case when t2.status is 'B' then 1 else 0 end) as BCount,
    ...
    sum(case when t2.code is null then 1 else 0 end) as NotPresentCount
from       t1
cross join t3
left join  t2 
on         t2.code = t1.code and t2.period = t3.period
group by   t3.period
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文