Skip to content
Advertisement

MySQL-Statement. How do i skip rows in query where all rows equal null

I have created a query to construct a table with the following code:

SELECT Date, 
    SUM(CASE WHEN UniqueId = 'NonComLong' THEN Value ELSE NULL END) AS 'NonComLong',
    SUM(CASE WHEN UniqueId = 'NonComShort' THEN Value ELSE NULL END) AS 'NonComShort',
        SUM(CASE WHEN UniqueId = 'NonComNetLong' THEN Value ELSE NULL END) AS 'NonComNetLong',
        SUM(CASE WHEN UniqueId = 'NonComPos' THEN Value ELSE NULL END) AS 'NonComPos',
        SUM(CASE WHEN UniqueId = 'TotalPositions' THEN Value ELSE NULL END) AS 'TotalPositions',
        SUM(CASE WHEN UniqueId = 'NonComPosShare' THEN Value ELSE NULL END) AS 'NonComPosShare'
FROM fundamental_data WHERE AttributeId = 160 AND Date >= '2011-06-14'
GROUP BY Date
ORDER BY Date; 

The above code returns the following table:

Image of table

I would like to write a piece of in which i can skip a row if all columns except the date column returns NULL. Is that possible?

Thanks in advance!

Advertisement

Answer

Assuming that column value is not nullable, you can add another condition to the WHERE clause that ensures that at least one of the conditions in the aggregate functions will be met:

SELECT ...
FROM fundamental_data 
WHERE 
    AttributeId = 160 
    AND Date >= '2011-06-14'
    AND UniqueId IN (
        'NonComLong',
        'NonComShort',
        'NonComNetLong',
        'NonComPos',
        'TotalPositions',
        'NonComPosShare'
    )

If value may be null, you would just add another condition:

WHERE
    ...
    AND value IS NOT NULL
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement