将变量传递给子查询

时间:2013-07-31 14:07:36

标签: mysql

我想从每个项目中提取所有客户的优惠,如果他们有多个优惠,我希望平均价值。

我有以下查询:

SELECT
@projectid := projects.id AS projectid,
(SELECT
  SUM(`offers`) FROM
  (SELECT AVG( `price` ) AS `offers`
    FROM `sales`
    WHERE `sales`.`projectid` = @projectid
    AND `sales`.`active` = 'yes'
    GROUP BY `sales`.`clientid`
  ) AS `average`
) AS `outstanding`
FROM projects
WHERE
projects.active = 'yes'
ORDER BY outstanding ASC 

我的问题是@projectid 传递到子查询中,我不明白我应该如何解决这个问题。

有人可以给我一些建议吗?

1 个答案:

答案 0 :(得分:0)

请记住,SQL是一种声明性语言,而不是命令式语言。使用JOIN和没有“变量”的子查询可以解决许多问题。所以......

......我不太明白 - 但是你只是需要“为每个项目提供每个客户的平均报价总和”,这样就可以了:

SELECT S.projectid, SUM(offers) FROM
  (
    SELECT projectid, clientid, AVG(price) as offers FROM sales WHERE active = 'yes'
    GROUP BY projectid, clientid
  ) AS S 
JOIN projects on S.projectid = projects.id
AND projects.active = "yes"
GROUP BY projectid

请参阅http://sqlfiddle.com/#!2/19d0f/24