Hcabnettek
Hcabnettek

Reputation: 12928

SQL Max Group By Query Help

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 WITH (NOLOCK)
WHERE biID = @biID

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

Thanks, ~ck

Upvotes: 1

Views: 440

Answers (4)

Stu Pegg
Stu Pegg

Reputation: 1317

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

Upvotes: 1

chris
chris

Reputation: 9993

can you not just do this?

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

Upvotes: 8

Marcus Adams
Marcus Adams

Reputation: 53830

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

Upvotes: 1

ChrisLively
ChrisLively

Reputation: 88064

How about

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

Upvotes: 1

Related Questions