sql总结特定的行而没有子查询返回多个行

发布于 2025-02-07 16:56:58 字数 2998 浏览 5 评论 0原文

有一些与此问题相似的帖子,但是我无法通过这些帖子找到解决此问题的解决方案。

我有以下两个桌子(我没有发布完整表格,要理解问题都需要太多):

表1:员工

emp_idfirst_namelast_name
102MichaelScott
108JimHalpert

表2:works_with

emp_id emp_id emp_idClient_idtotal_sales
102401267,000
10240615,000
10840222,500
10840312,000

如果此表数据不够,我可以返回并添加更多。

我遇到的问题是此代码:

SELECT e.emp_id AS ID, 
e.first_name AS 'First Name', 
e.last_name AS 'Last Name', 
ww.total_sales = (SELECT SUM(ww.total_sales) 
                 FROM works_with
                 WHERE e.emp_id = ww.emp_id
                 ) AS Sales
FROM (employee e, works_with ww)
INNER JOIN works_with ON ww.emp_id = e.emp_id;

当我运行这样的代码时,我会收到错误:“ SQL错误(1242):子查询返回超过1行。”

我在网上看到了一个解决方案,该解决方案说要在子查询之前添加“任何”,但这是结果表:

ID名称姓氏销售102
MichaelScott0

是我想要结果表的样子:

ID名字姓氏姓氏销售
102MichaelScott282,000
108JimHalper34,500

我对如何解决此问题感到困惑。任何帮助将不胜感激!

There are a few posts that seem similar to this problem, but I cannot find the solution to this problem through those posts.

I have the following two tables that I am working with (I'm not posting the full table, just as much is needed to understand the problem):

Table 1: employee

emp_idfirst_namelast_name
102MichaelScott
108JimHalpert

Table 2: works_with

emp_idclient_idtotal_sales
102401267,000
10240615,000
10840222,500
10840312,000

If this table data is not sufficient, I can go back and add more.

The issue I am having is with this code:

SELECT e.emp_id AS ID, 
e.first_name AS 'First Name', 
e.last_name AS 'Last Name', 
ww.total_sales = (SELECT SUM(ww.total_sales) 
                 FROM works_with
                 WHERE e.emp_id = ww.emp_id
                 ) AS Sales
FROM (employee e, works_with ww)
INNER JOIN works_with ON ww.emp_id = e.emp_id;

When I run the code like this, I get the error: "SQL Error (1242): Subquery returns more than 1 row."

I saw a solution online that said to add "Any" before the subquery, but this is the resulting table:

IDFirst NameLast NameSales
102MichaelScott0

This is what I want the resulting table to look like:

IDFirst NameLast NameSales
102MichaelScott282,000
108JimHalper34,500

I am confused as to how I would fix this. Any help is greatly appreciated!

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

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

发布评论

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

评论(1

小姐丶请自重 2025-02-14 16:56:58

这应该为您提供所需的结果,而表1是您提到的第一张表,表2是第二个表2

SELECT
    T1.*
    SUM(T2.TOTAL_SALES)
FROM <TABLE1> T1
    JOIN <TABLE2> T2 ON T1.EMP_ID = T2.EMP_ID
GROUP BY
    T1.EMP_ID, T1.FIRST_NAME, T1.LAST_NAME

This should give you the results you need where table 1 is the first table you mentioned and table 2 is the second

SELECT
    T1.*
    SUM(T2.TOTAL_SALES)
FROM <TABLE1> T1
    JOIN <TABLE2> T2 ON T1.EMP_ID = T2.EMP_ID
GROUP BY
    T1.EMP_ID, T1.FIRST_NAME, T1.LAST_NAME
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文