【问题标题】:Join two MySQL SELECT statements containing one WHERE clause加入两个包含一个 WHERE 子句的 MySQL SELECT 语句
【发布时间】:2016-03-18 23:33:38
【问题描述】:

如何将下面的两个 select 语句合并为一个语句?我希望结果出现在一张表中。感谢您的帮助。

第一个陈述-

SELECT Account_ID, SUM(Profit_Loss) AS Starting_Balance
FROM client_ledger_history
WHERE Summary = 'Cash In'
GROUP BY Account_ID WITH ROLLUP

第二个陈述 -

SELECT
    client_ig_client_list.Account_ID,
    client_ig_client_list.`Name`,
    Share_Status,
    Forex_Status,
    Index_Status,
    Share_Weighting,
    Forex_Weighting,
    Index_Weighting,
    SUM(
        client_ledger_history.Profit_Loss
    ) AS Current_Balance
FROM
    client_ledger_history
LEFT JOIN client_ig_client_list ON client_ig_client_list.Account_ID = client_ledger_history.Account_ID
GROUP BY
    Account_ID WITH ROLLUP

【问题讨论】:

  • 如果您提供示例数据和所需结果,您的问题会更清楚。

标签: mysql join where-clause


【解决方案1】:

你应该加入一个嵌套表

SELECT
client_ig_client_list.Account_ID,
Starting_Balance,
client_ig_client_list.`Name`,
Share_Status,
Forex_Status,
Index_Status,
Share_Weighting,
Forex_Weighting,
Index_Weighting,
SUM(client_ledger_history.Profit_Loss) AS Current_Balance 
FROM
    client_ledger_history LEFT JOIN client_ig_client_list ON client_ig_client_list.Account_ID = client_ledger_history.Account_ID 
LEFT JOIN 
(SELECT Account_ID, SUM(Profit_Loss) AS Starting_Balance 
FROM client_ledger_history WHERE Summary = 'Cash In' GROUP BY Account_ID WITH ROLLUP) as client_ledger_aggreagated_history 
ON client_ledger_aggreagated_history.Account_ID = client_ledger_history.Account_ID
    GROUP BY Account_ID WITH ROLLUP

【讨论】:

  • 感谢@MrMush,但是当我尝试您的陈述时出现以下错误。 [错误] 1054 - '字段列表'中的未知列'client_ledger_aggreagated_history.Profit_Loss'
  • 糟糕,已修复,请重试。
猜你喜欢
  • 2012-01-26
  • 1970-01-01
  • 2010-12-07
  • 2018-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-30
相关资源
最近更新 更多