如何完成此SQL Server 2008查询?

时间:2013-06-13 21:54:47

标签: sql-server-2008

我需要一个SQL 2008查询来返回所有拥有>的消费者1个用户字段记录与相同的USERFIELDUUID相关联 - 换句话说,所有那些拥有重复用户字段记录的消费者。

CONSUMER_USER_FIELD记录中的相关字段:

CONSUMER_USER_FIELD_UUID - primary key
USERFIELD_UUID
CONSUMER_UUID

CONSUMER记录中的相关字段:

CONSUMER_UUID - primary key

USER_FIELD记录中的相关字段:

USERFIELD_UUID - primary key
CONSUMER_UUID
FIELD_NAME
PROMPT

我的代码可以找到所有拥有> 1个CONSUMER_USER_FIELD(CUF)记录的消费者。我只是遇到了“并且相同的userfield_uuid在>这些CUF记录中的1个”部分。

这是我到目前为止所拥有的:

SELECT c.consumer_uuid 
FROM   consumer c 
       INNER JOIN consumer_user_field cuf 
               ON cuf.consumer_uuid = c.consumer_uuid 
WHERE  1 < (SELECT count(user_field_uuid) 
            FROM   consumer_user_field cuf2 
            WHERE  cuf2.consumer_uuid = c.consumer_uuid) 

我是否在正确的轨道上?我现在只需要一个HAVING条款吗?

1 个答案:

答案 0 :(得分:2)

SELECT C.*
FROM
   dbo.Consumer C
WHERE
   EXISTS (
      SELECT *
      FROM dbo.Consumer_User_Field CUF
      WHERE C.Consumer_UUID = CUF.Consumer_UUID
      GROUP BY CUF.USERFIELD_UUID
      HAVING Count(*) >= 2
   )
;

P.S。对于任何想要抱怨您无法使用SELECT *进行GROUP BY的人:您可以在EXISTS条款中。请在发布之前自己尝试一下。 :)

你也可以这样做:

SELECT C.*
FROM
   dbo.Consumer C
   INNER JOIN (
      SELECT DISTINCT CUF.Consumer_UUID
      FROM dbo.Consumer_User_Field CUF
      GROUP BY
         CUF.Consumer_UUID,
         CUF.USERFIELD_UUID
      HAVING Count(*) >= 2
   ) U ON C.Consumer_UUID = U.Consumer_UUID
;

还有另一个想法:

SELECT C.*
FROM
   dbo.Consumer C
WHERE
   EXISTS (
      SELECT *
      FROM
         dbo.Consumer_User_Field CUF
      WHERE
         C.Consumer_UUID = CUF.Consumer_UUID
         AND EXISTS (
            SELECT *
            FROM dbo.Consumer_User_Field CUF2
            WHERE
               CUF.Consumer_UUID = CUF2.Consumer_UUID
               AND CUF.USERFIELD_UUID <> CUF2.USERFIELD_UUID
         )
   )
;

从逻辑角度来看,这些是等效查询。它们的表现可能不同 - 您应该尝试它们,看看哪种效果最好。如果你这样做,请告诉我吗?