Select a Column in SQL not in Group By

前端 未结 7 1325
忘了有多久
忘了有多久 2020-11-30 02:25

I have been trying to find some info on how to select a non-aggregate column that is not contained in the Group By statement in SQL, but nothing I\'ve found so far seems to

相关标签:
7条回答
  • 2020-11-30 02:56

    The direct answer is that you can't. You must select either an aggregate or something that you are grouping by.

    So, you need an alternative approach.

    1). Take you current query and join the base data back on it

    SELECT
      cpe.*
    FROM
      Filteredfmgcms_claimpaymentestimate cpe
    INNER JOIN
      (yourQuery) AS lookup
        ON  lookup.MaxData           = cpe.createdOn
        AND lookup.fmgcms_cpeclaimid = cpe.fmgcms_cpeclaimid
    

    2). Use a CTE to do it all in one go...

    WITH
      sequenced_data AS
    (
      SELECT
        *,
        ROW_NUMBER() OVER (PARITION BY fmgcms_cpeclaimid ORDER BY CreatedOn DESC) AS sequence_id
      FROM
        Filteredfmgcms_claimpaymentestimate
      WHERE
        createdon < 'reportstartdate'
    )
    SELECT
      *
    FROM
      sequenced_data
    WHERE
      sequence_id = 1
    

    NOTE: Using ROW_NUMBER() will ensure just one record per fmgcms_cpeclaimid. Even if multiple records are tied with the exact same createdon value. If you can have ties, and want all records with the same createdon value, use RANK() instead.

    0 讨论(0)
提交回复
热议问题