我想从Contracts表返回所有行,但是第二个WHERE子句只产生非空的行。 (换句话说,在下面的代码中,CAD'限制意味着大约一半的可能行没有以加元交易的值,因此不会返回 - 而我希望返回的所有可能行显示NULL值(如果适用) )。
我认为它是一个左自我加入,但我正在努力学习语法(和/或我是否需要进行内部选择),
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
答案 0 :(得分:3)
使用条件聚合:
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;
答案 1 :(得分:0)
对于未来的读者,Thorsten回答了已发布的问题,但根据他的回答,无法将其付诸实践。因此,我不得不这样编码:
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;
答案 2 :(得分:0)
使用分组..
通过CompanyID从Adjusters组中选择*;