SQL查询返回null结果但数据库中仍有值

时间:2017-12-20 06:23:37

标签: sql sql-server

我正在创建一个需要连接两个表并创建子查询的报告。以下是代码

WITH temp_ticket_rows (client_id, last_name,first_name, pet_name) AS 
(   
    SELECT 
        C.fldClientID, C.fldLastName, C.fldFirstName, P.fldName     
    FROM 
        [OneTwoThreePet].[dbo].[tblPets] P   
    RIGHT OUTER JOIN 
        tblClients C ON P.fldClientID = C.fldClientID
),  temp_tips ([Last Name], [First Name], [Pet Name]) AS 
( 
    SELECT  
        C.fldLastName, C.fldFirstName, 
        (STUFF((SELECT DISTINCT ', ' + P.fldName[text()]
                FROM [OneTwoThreePet].[dbo].[tblPets] P
                WHERE P.fldClientID = C.fldClientID 
                  AND p.fldInactive IN ('0','')
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2,' ')) AS [Pet Name]   
    FROM 
        temp_ticket_rows P
    LEFT OUTER JOIN
        tblClients C ON C.fldClientID = P.client_id
) 
SELECT
    UPPER(LEFT([Last Name], 1)) + LOWER(SUBSTRING([Last Name], 2, LEN([Last Name]))) AS [LAST NAME],
    UPPER(LEFT([First Name], 1)) + LOWER(SUBSTRING([First Name], 2, LEN([First Name]))) AS [FIRST NAME],
    [Pet Name] AS [PET NAME],
    COUNT (*) AS [PET NUMBER] 
FROM
    temp_tips 
--WHERE [Pet Name] IS NOT NULL
GROUP BY [Last Name], [First Name], [Pet Name] 
ORDER BY [Last Name] ASC

上面的查询结果给出了一些null,因为有值,所以不应该存在。下面是查询结果,您可以看到空值,但宠物数量计为1

query results 更改了查询的结构,如下所示

WITH temp_ticket_rows (client_id, last_name,first_name, pet_name) AS 
( 
    SELECT 
        C.fldClientID, C.fldLastName, C.fldFirstName, P.fldName
    FROM
        [OneTwoThreePet].[dbo].[tblPets] P
    INNER JOIN 
        tblClients C ON P.fldClientID = C.fldClientID
), temp_tips ([Last Name], [First Name], [Pet Name]) AS 
( 
    SELECT
        C.fldLastName, C.fldFirstName,
        (STUFF((SELECT DISTINCT ', ' + P.fldName[text()]
                FROM [OneTwoThreePet].[dbo].[tblPets] P
                WHERE P.fldClientID = C.fldClientID 
                  AND p.fldInactive IN ('0', '')
                FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, ' ')) as [Pet Name] 
    FROM 
        temp_ticket_rows P
    LEFT OUTER JOIN
        tblClients C ON C.fldClientID = P.client_id
)
SELECT
    UPPER(left( [Last Name],1)) + LOWER(SUBSTRING([Last Name],2,LEN([Last Name]))) AS [LAST NAME],
    UPPER (left ([First Name],1)) + LOWER(SUBSTRING([First Name],2,LEN([First Name]))) AS [FIRST NAME],
    [Pet Name] AS [PET NAME],
    COUNT ([Pet Name]) AS [PET NUMBER]
FROM
    temp_tips 
--WHERE [Pet Name] IS NOT NULL
GROUP BY 
    [Last Name], [First Name], [Pet Name]
ORDER BY 
    [Last Name] ASC

结果是这样的:

query results

1 个答案:

答案 0 :(得分:1)

您已使用COUNT (*) AS [PET NUMBER],因此即使PET NAME为NULL,您也会将结果设为1

COUNT (*) AS [PET NUMBER]更改为COUNT ([PET NUMBER]) AS [PET NUMBER]并进行检查。您必须将结果设为0,[PET NUMBER]为空。