Select first row of group with criteria

与世无争的帅哥 提交于 2021-01-27 19:11:07

问题


I have a table in this format:

FieldA   FieldB   FieldC
1111     ABC      X
1111     DEF      Y
1111     GHI      X
2222     JKL      Y
2222     MNO      X
3333     PQR      U
3333     STT      U

I want to select one FieldB per FieldA with preference to X in FieldC (if there no X, pick another one).

I've tried using the RANK function with PARTITION BY but I find it too inconsistent and I have now reached a wall.

My output would look like this:

 FieldA   FieldB   FieldC
    1111     ABC      X
    2222     MNO      X
    3333     PQR      U

Query:

Select
rank() over (partition by Field3 order by Field1),
Field,1 Field2, Field3
FROM table
ORDER BY Field1, Field3

I'm guessing I'd need to put that query inside a sub-query...


回答1:


You can use ROW_NUMBER like this:

SELECT FieldA, FieldB, FieldC
FROM (
   SELECT FieldA, FieldB, FieldC,
          ROW_NUMBER() OVER (PARTITION BY FieldA
                             ORDER BY CASE 
                                         WHEN FieldC = 'X' THEN 1
                                         ELSE 2
                                      END,
                                      FieldB) AS rn 
   FROM mytable) AS t
WHERE t.rn = 1

The above query picks one record out of each FieldA partition. It prioritizes records having FieldC = 'X' over all other records.



来源:https://stackoverflow.com/questions/43371057/select-first-row-of-group-with-criteria

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!