简体   繁体   中英

Group By Proper Usage

TL;DR How do I return columns without adding them to the GROUP BY clause in MSSQL ? The criminal statement is below.

Hello Everyone, So I recently asked this question and got a great solution which I was able to dissect and reassemble to suite my problem. Here is the final result

WITH UC AS
(
    SELECT OSJ.opportunityid, OS.status,
           ROW_NUMBER() OVER (PARTITION BY OSJ.opportunityid ORDER BY creationdate DESC) RN
    FROM Opportunitystatusjoin OSJ
    JOIN OpportunityStatus OS ON OSJ.opportunitystatusid = OS.opportunitystatusid
)
SELECT O.opportunityid , O.salesperson ,
    MAX( CASE 
        WHEN RN = 1
            THEN UC.status
        END ) AS MostRecent ,
    MAX( CASE 
        WHEN RN = 2
            THEN UC.status
        END ) AS SecondMostRecent
FROM Opportunity O
JOIN UC ON UC.opportunityid = O.opportunityid
WHERE UC.RN <= 2
GROUP BY O.opportunityid , O.salesperson

Now if I want to return more columns from the Opportunity table ie O.shoesize, O.favorite_color, I have to add them to my GROUP BY clause. But I just get a dirty feeling because I am not trying to group the other columns, I just want them to show up with their respective opportunity.

A blog I found on the internet said to stuff your GROUP BY clauses as far in to your nested selects as possible. However, since I am using the first statement ( "with UC...") that seems to make things less intuitive. What is a smart way to include other columns from my table without adding them to the GROUP BY clause.

如果对于您要分组的所有内容,这些列的值都相同,那么您可以执行以下操作:

SELECT col1, col2, MAX(col3) FROM table GROUP BY col1, col2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM