0

Azure SQL Server 2016 - I'm having trouble with the syntax to combine TOP, MAX and DATALENGTH to get a list of the Top 50 records from a table by DATALENGTH of a specific field.

The field I need to do the DATALENGTH on is called Text. I don't actually want the Text field returned in the results - What I want returned are fields called CaptureId and TaskSourceId from the 50 records with the largest DATALENGTH in the Text field, as well as the DATALENGTH amount.

I tried this, but it did not work, with an error about CaptureId not being contained in an aggregate function or GROUP BY clause.

SELECT TOP 50 
    CaptureId, 
    TaskSourceId, 
    MAX(DATALENGTH([Text]))
FROM 
    Data.Capture

Can someone please help me correct this query?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Stpete111
  • 3,109
  • 4
  • 34
  • 74

1 Answers1

2

You don't need max. Just sort the records:

select top 50 
  captureid, tasksourceid, datalength(text) as text_len
from data.capture
order by datalength(text) desc

This will not care about ties and return up to 50 rows.

If you want to account ties regarding text field data length, use top 50 with ties instead of simple top 50. It may return more than 50 records in this case.

Kamil Gosciminski
  • 16,547
  • 8
  • 49
  • 72