抓住不止一次出现的客户的详细信息

时间:2012-07-03 08:17:21

标签: sql sql-server

我在下面的代码中遇到了一个奇怪的错误。 No column was specified for column 2 of 'no1'. 据我所知,它应该工作。我只是想在收据上多次获取有关客户不止一次存在的客户的详细信息。

SELECT
    CM.ClientID,
    CPN.Birthdate,
    CM.ClientPassword
FROM 
    dbo.ClientMaster AS CM
    JOIN dbo.ClientPerson AS CPN ON (CM.ClientID = CPN.ClientID)
    JOIN dbo.ClientProduct AS CP ON (CPN.ClientID = CP.ClientID)
WHERE 
    CM.ClientID IN (
                    SELECT 
                        no1.ClientID 
                    FROM 
                        (
                        SELECT 
                            CM.ClientID,
                            COUNT(*)
                        FROM 
                            dbo.ClientMaster AS CM
                            JOIN dbo.ClientPerson AS CPN ON (CM.ClientID = CPN.ClientID)
                            JOIN dbo.ClientProduct AS CP ON (CPN.ClientID = CP.ClientID)
                        WHERE
                            CP.PolicyNo IN (SELECT PolicyNo FROM Receipts)
                            AND CM.ClientID IS NOT NULL
                            AND Birthdate IS NOT NULL
                            AND ClientPassword IS NOT NULL
                        GROUP BY
                            CM.ClientID
                        HAVING 
                            COUNT(*)>1
                        ) AS no1
                    )

啊没有意识到你不需要Count(*)中的Select。多谢你们! 这就是我最终的目标。

SELECT DISTINCT
    CM.ClientID,
    CPN.Birthdate,
    CM.ClientPassword
FROM 
    dbo.ClientMaster AS CM
    JOIN dbo.ClientPerson AS CPN ON (CM.ClientID = CPN.ClientID)
    JOIN dbo.ClientProduct AS CP ON (CPN.ClientID = CP.ClientID)
WHERE 
    CM.ClientID IN (
                        SELECT 
                            ClientID 
                        FROM 
                            Receipts
                        GROUP BY
                            ClientID
                        HAVING 
                            COUNT(*)>1
                        )
    AND CM.ClientID IS NOT NULL
    AND Birthdate IS NOT NULL
    AND ClientPassword IS NOT NULL

2 个答案:

答案 0 :(得分:2)

您的COUNT(*)列需要一个名称,例如:

 COUNT(*) AS RecordCount

答案 1 :(得分:1)

您不需要为此嵌套相同的查询两次。你可以这样做:

SELECT
    CM.ClientID,
    CPN.Birthdate,
    CM.ClientPassword
FROM 
    dbo.ClientMaster AS CM
    JOIN dbo.ClientPerson AS CPN ON (CM.ClientID = CPN.ClientID)
    JOIN dbo.ClientProduct AS CP ON (CPN.ClientID = CP.ClientID)
GROUP BY CM.ClientID, CPN.Birthdate, CM.ClientPassword
HAVING COUNT(CM.ClientID) > 1