SQL Return every row even if Null values

…衆ロ難τιáo~ 提交于 2019-12-13 10:33:09

问题


I want to return all rows from a Contracts table but a second WHERE clause yields only rows which are not null. (In other words in the code below the 'CAD' restriction means approx half the possible rows have no value traded in Canadian Dollars and thus are not returned --whereas I want all possible rows returned showing NULL values where applicable).

I figure it's a Left Self Join but am struggling with the syntax (and/or whether I need to do an Inner Select),

 SELECT MeasurableID,
     EntityID,
     MIN (ContractPrice) AS LowPrice,
     MAX (ContractPrice) AS HighPrice

 FROM dbo.Contracts

 WHERE dbo.Contracts.MeasurableID = 2018
  AND  Contracts.CurrencyCode IN ( 'CAD' ) 

 GROUP BY
  dbo.Contracts.MeasurableID,
  dbo.Contracts.EntityID  

回答1:


Use conditional aggregation:

SELECT  
  MeasurableID,
  EntityID,
  MIN (CASE WHEN CurrencyCode = 'CAD' THEN ContractPrice END) AS LowPrice,
  MAX (CASE WHEN CurrencyCode = 'CAD' THEN ContractPrice END) AS HighPrice
FROM dbo.Contracts
WHERE MeasurableID = 2018
GROUP BY MeasurableID, EntityID
ORDER BY MeasurableID, EntityID;



回答2:


For future readers, Thorsten answered the question as posted but per comments below his answer it could not be put into practice. Thus instead I have had to code it this way:

    SELECT
        t1.MeasurableID,
        t1.EntityID,
        t2.HIGH,
        t2.LOW
    FROM
        (
            SELECT
                MeasurableID,
                EntityID
            FROM
                Contracts
            WHERE
                MeasurableID IN (2017, 2018)
            GROUP BY
                MeasurableID,
                EntityID
        ) t1
    LEFT JOIN (
        SELECT
            MeasurableID,
            EntityID,
            MAX (ContractPrice) AS HIGH,
            MIN (ContractPrice) AS LOW
        FROM
            Contracts
        WHERE
            MeasurableID IN (2017, 2018)
        AND CurrencyCode IN ('CAD', 'BTC')
        GROUP BY
            MeasurableID,
            EntityID
    ) t2 ON t1.MeasurableID = t2.MeasurableID
    AND t1.EntityID = t2.EntityID
    ORDER BY
        t1.MeasurableID,
        t1.EntityID;



回答3:


used group by..

select * from Adjusters group by CompanyID;



来源:https://stackoverflow.com/questions/46497384/sql-return-every-row-even-if-null-values

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