如何使用具有多个子查询的sql进行分组

时间:2013-09-19 10:20:55

标签: mysql sql fastreport

我正在尝试将SC_FRAMES.GROUPPRODUCTTYPE添加到此语句中:

SELECT
  SC_JOBS.CREATIONDATE,

  (SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE SC_FRAMES.GROUPPRODUCTTYPE = 'ABC'    AND SC_FRAMES.JOBID = SC_JOBS.JOBSID AND SC_JOBS.INVOICEDATE < '1990-01-01') AS Product1,

  (SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE SC_FRAMES.GROUPPRODUCTTYPE = 'XYZ'    AND SC_FRAMES.JOBID = SC_JOBS.JOBSID AND SC_JOBS.INVOICEDATE < '1990-01-01') AS Product2 

FROM
  SC_JOBS
INNER JOIN
  SC_FRAMES ON SC_FRAMES.JOBID = SC_JOBS.JOBSID
WHERE
  SC_JOBS.CREATIONDATE BETWEEN :StartDate AND :EndDate
ORDER BY
  SC_JOBS.CREATIONDATE

有什么建议吗?

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT
  SC_JOBS.CREATIONDATE,
  (SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE SC_FRAMES.GROUPPRODUCTTYPE = 'ATI'    AND SC_FRAMES.JOBID = SC_JOBS.JOBSID AND SC_JOBS.INVOICEDATE < '1990-01-01') AS Product 1,
  (SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE SC_FRAMES.GROUPPRODUCTTYPE = 'ATI'    AND SC_FRAMES.JOBID = SC_JOBS.JOBSID AND SC_JOBS.INVOICEDATE < '1990-01-01') AS Product 2 
FROM
  SC_JOBS
INNER JOIN
  SC_FRAMES ON SC_FRAMES.JOBID = SC_JOBS.JOBSID
WHERE
  SC_JOBS.CREATIONDATE BETWEEN :StartDate AND :EndDate
GROUP BY
  SC_FRAMES.GROUPPRODUCTTYPE
ORDER BY
  SC_JOBS.CREATIONDATE

答案 1 :(得分:0)

GROUP BY SC_FRAMES.GROUPPRODUCTTYPE声明结束后和WHERE声明之前添加ORDER BY。同时将AS值更改为不包含空格,因为我过去曾遇到过这样的问题,因此使用Product1而不是Product 1

答案 2 :(得分:0)

我想你想要一个这样的查询:

SELECT f.GROUPPRODUCTTYPE,
       MIN(j.CREATIONDATE),
       SUM(case when j.INVOICEDATE < '1990-01-01' then j.GROSSEXCLVAT else 0
           end) as Product1
FROM SC_JOBS INNER j JOIN
     SC_FRAMES f
     ON f.JOBID = j.JOBSID
WHERE j.CREATIONDATE BETWEEN :StartDate AND :EndDate
GROUP BY f.GROUPPRODUCTTYPE
ORDER BY min(j.CREATIONDATE);

它根据发票日期用条件聚合替换子查询。