开发者

SQL Max Group By Query Help

开发者 https://www.devze.com 2023-01-01 05:39 出处:网络
I have a quick question. How do I select the two values I need in one query? Currently I\'m doing this, which works fine, but it\'s obviously running two queries when one should do the trick. I tried

I have a quick question. How do I select the two values I need in one query? Currently I'm doing this, which works fine, but it's obviously running two queries when one should do the trick. I tried MAX(columnA) and GROUP BY ColumnB, but that returns multiple row. I only want one row returned.

DECLARE @biID  bigint  
, @dtThreshold      DateTime 

  SELECT @biID = MAX(biID)
FROM tbPricingCalculationCount WITH (NOLOCK)

  SELECT @dtThreshold = dtDateTime
FROM tbPricingCalculationCount W开发者_C百科ITH (NOLOCK)
WHERE biID = @biID

I would like both those variables to be set correctly in one query. How can I do that?

Thanks, ~ck


can you not just do this?

SELECT TOP 1 @biID = biID, @dtThreshold = dtDateTime 
  FROM tbPricingCalculationCount WITH (NOLOCK) 
ORDER BY biID DESC;


How about:

DECLARE
  @biID bigint,
  @dtThreshold DateTime 

SELECT
  @dtThreshold = A.dtDateTime,
  @biID = B.biID
FROM tbPricingCalculationCount A
  INNER JOIN (SELECT MAX(biID) biID
              FROM tbPricingCalculationCount) B
    ON A.biID = B.biID

If you're not using the biID elsewhere, you can even trim it to:

DECLARE
  @dtThreshold DateTime 

SELECT
  @dtThreshold = A.dtDateTime
FROM tbPricingCalculationCount A
  INNER JOIN (SELECT MAX(biID) biID
              FROM tbPricingCalculationCount) B
    ON A.biID = B.biID


How about

SELECT TOP 1 @biID = biID, @dtThreshold = dtDateTime
FROM tbPricingCalculationCount (NOLOCK)
ORDER BY biID desc


This returns dtDateTime for the row with the largest biID:

SELECT t1.dtDateTime
FROM tbPricingCalculationCount t1
LEFT JOIN tbPricingCalculationCount t2
ON t2.biID > t1.biID
WHERE t2.biID IS NULL

If more than one row shares the same "largest" biID, then you need to limit the results to one using TOP:

SELECT TOP 1 t1.dtDateTime
FROM tbPricingCalculationCount t1
LEFT JOIN tbPricingCalculationCount t2
ON t2.biID > t1.biID
WHERE t2.biID IS NULL
0

精彩评论

暂无评论...
验证码 换一张
取 消