问题
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