Select individual records only

青春壹個敷衍的年華 提交于 2019-12-12 01:02:14

问题


I have a table as such

custno, type, color
A1234, B, Red
A1234, C, Blue
A1277, B, Red
A1288, A, Black
A1288, B, Red
A1289, A, Black

I need to retrieve only the unique records A1277 and A1289 that are only found once.


回答1:


This will display the custNO on the result list,

SELECT  custNo
FROM    tableName
GROUP   BY custNO
HAVING  COUNT(*) = 1

but if you want to get the whole row,

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  custNo
            FROM    tableName
            GROUP   BY custNO
            HAVING  COUNT(*) = 1
        ) b ON a.custNo = b.custNo
  • SQLFiddle Demo (both queries)



回答2:


SELECT custno
FROM yourTable
GROUP BY custno
HAVING COUNT(*) = 1

Example Fiddle




回答3:


Try this as this will prevent costly join operation--

SELECT custno,type,color FROM ( SELECT custno, type, color, COUNT(custno) OVER(PARTITION BY custno) CNT FROM tableName )TMP WHERE CNT=1



来源:https://stackoverflow.com/questions/15364846/select-individual-records-only

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