使用group by对select语句进行分组

时间:2014-08-28 11:08:24

标签: sql group-by inner-join multiple-tables

使用group by对select语句进行分组

SELECT
    k.Ivalue, k.JOBDESCRIPTION , 
    count( k.Ivalue) as TOTAL 
FROM
    (SELECT  
        a."ID" as Ivalue, b."JOBDESCRIPTION", rq."CURRENTSTATUS" 
     FROM 
        tblG2o_Requests a
     INNER JOIN
        tblG2o_JOBS b ON a."JOBPOSTID" = b."ID"
     INNER JOIN
        (SELECT 
            r.REQUESTID, ir."CURRENTSTATUS" 
         FROM 
            TBLG2O_RESULTSPOOL r 
         INNER JOIN 
            tblG2o_Requests ir ON r.RequestID = ir."ID" 
         WHERE 
            r.ShortListed = '1') rq ON rq.REQUESTID = a."ID"
     WHERE
         "ACTIVE" = '1' 
         AND "DATECOMPLETED" IS NULL
     ORDER BY 
         "REQUESTDATE" DESC) k 
GROUP BY 
    k.JOBDESCRIPTION 

2 个答案:

答案 0 :(得分:1)

问题是什么?您似乎缺少group by子句,并且您不需要在字段名称周围使用双引号,除非您在其中包含空格,即使如此,如果使用TSQL,您也可以优先使用[]。

我必须在子查询中删除ORDER BY,除非其他条件要求它(如TSQL中的TOP n),否则不允许这样做

SELECT
      k.Ivalue
    , k.JOBDESCRIPTION
    , COUNT(k.Ivalue) AS TOTAL
FROM (
            SELECT
                  a.ID AS Ivalue
                , b.JOBDESCRIPTION
                , rq.CURRENTSTATUS
            FROM tblG2o_Requests a

                  INNER JOIN tblG2o_JOBS b
                              ON a.JOBPOSTID = b.ID
                  INNER JOIN (
                              SELECT
                                    r.REQUESTID
                                  , ir.CURRENTSTATUS
                              FROM TBLG2O_RESULTSPOOL r
                                    INNER JOIN tblG2o_Requests ir
                                                ON r.RequestID = ir.ID
                              WHERE r.ShortListed = '1'
                        ) rqenter
                              ON rq.REQUESTID = a.ID
            WHERE ACTIVE = '1'
                  AND DATECOMPLETED IS NULL
      ) k
GROUP BY
      k.Ivalue
    , k.JOBDESCRIPTION

答案 1 :(得分:0)

终于工作了

选择       k.Ivalue     ,l.JOBDESCRIPTION     ,k.TOTAL, k.CURRENTSTATUS FROM(             选择                   a.ID AS Ivalue          ,b.ID作为JobPostID                 ,rq。“CURRENTSTATUS” ,COUNT(a.ID)AS TOTAL             从tblG2o_Requests a

              INNER JOIN tblG2o_JOBS b
                          ON a."JOBPOSTID" = b.ID
              INNER JOIN (
                          SELECT
                                r."REQUESTID"
                              , ir."CURRENTSTATUS"
                          FROM TBLG2O_RESULTSPOOL r
                                INNER JOIN tblG2o_Requests ir
                                            ON r."REQUESTID" = ir.ID
                          WHERE r."SHORTLISTED" = 1
                    ) rq

                          ON rq."REQUESTID" = a.ID
        WHERE ACTIVE = '1'
              AND DATECOMPLETED IS NULL 

GROUP BY       a.ID,b.ID ,rq。“CURRENTSTATUS”)k k.JobPostID = l.ID

上的内连接tblG2o_JOBS l
enter code here