How to get the value of max length in sql server - sql

i would like to ask you if there is a way to get the value of maxlength of column in ms sql server.
For example in the table A we have:
id | value
----+--------
1 | 0123
2 | 00034567
3 | 547
The desired result for this data set is 00034567.
Wherever i have searched for this problem i get the answer select max(len(value)) which is not what i need, because it gives the max number of characters of the value and not the value itself.
Any ideas?

SELECT TOP 1 t.value
FROM table AS t
ORDER BY LEN(t.value) DESC

Sort by length and take the first row:
select top 1 value
from mytable
order by len(value) desc
If you want ties:
select value
from mytable
where len(value) = (select max(len(value)) from mytable)
Or more efficient but SQL Server specific:
select value from (
select value,
rank() over (order by len(value) desc) rank
from mytable) x
where rank = 1
See SQLFiddle for last one.

the sql you use is correct, u just have to cast it to an nvarchar

Related

How to get the smallest unique integer from a table in SQLite

I have a table that has two columns, name and number. I'd like to get the smallest unique number from the provided table. for example
name
number
john
1
abbey
3
afton
2
mike
1
lucas
5
jack
2
jake
4
tony
3
For example, the smallest value here is 1 but the smallest unique value is 4
How could I make a query in SQLite that can do that?
I did see this post but it's not what I want
Edit: This is the code I tried
Select a.name, a.number
From Result a
Having count(a.smallest) = 1
Group By a.smallest;
It returned "Error: near line XX: near "Group": syntax error"
I also tried
Select a.name, a.number
From Result a
Where count(a.smallest) = 1
Group By a.smallest;
But it returned "Error: near line XX: misuse of aggregate: count()"
You may try aggregating your table by the number, restricting to numbers only appearing once, and then retaining the smallest number:
SELECT number
FROM yourTable
GROUP BY number
HAVING COUNT(*) = 1
ORDER BY number
LIMIT 1;
Using ROW_NUMBER:
SELECT *
FROM (SELECT a.*, COUNT(*) OVER(PARTITION BY number) AS cnt
FROM Result a) sub
WHERE cnt = 1
ORDER BY number
LIMIT 1;
Output:
name number cnt
jake 4 1
db<>fiddle demo
You can group by number and set the condition in the HAVING clause that the number is unique.
Then pick the smallest number with MIN() window function:
SELECT DISTINCT MIN(number) OVER () AS min_number
FROM tablename
GROUP BY number
HAVING COUNT(*) = 1;
See the demo.

Stuck to select maximum row

I have a table with columns:
ID | FULLNAME | VALUE
01 Joseph 10
02 Sam 50
... ... ...
I need to select row with maximum value, and show info like
FULLNAME | VALUE
I tried using group function MAX(), but I can't select fullname, because if I use it as a GROUP BY expression, it will select max in groups.
Other way, is to use WITH statement, order table by value desc, use
rank() OVER (PARTITION BY ID) AS max_id
function and maximum value will be on max_id = 1, and then use
WHERE max_id = 1
to remove other rows.
But I think there is a way to do this better and I can't find one.
UPDATE:
A tricky solution to this problem is
SELECT *
FROM t t1
LEFT JOIN t t2 ON t1.value<t2.value
WHERE t2.value IS NULL
The simplest way is to sort the data and pull one row:
select t.*
from t
order by value desc
fetch first 1 row only;
If you want ties, you can add with ties to the fetch first.
Another method is:
select t.*
from t
where t.value = (select max(t2.value) from t t2);
This can have very good performance with an index on value.

select max value and another column

id value
2 20
1 30
3 15
5 25
I have this table and want to get max value and id. When i use select id,max(value) i've got 2,30 but the right answer is 1,30. I really need to get your attention.
Thank you very much
select id, value from `table` order by value desc limit 1
You can try using subquery
select * from tablename
where value in (select max(value) from tablename)
SELECT *
FROM `tablename`
WHERE value=(SELECT
MAX(value) as value
FROM tablename)
You can check this query. Giving result according your requirement.
SELECT top 1 id,max(value) FROM table
GROUP BY id
ORDER BY max(value) desc
Use subquery
select *
from t
where value = (select max(value) from table)
From the #Thorsten comments i noted that 1st query will return all ties of max value.
Or you can use order by with limit if it is mysql
select *
from table
order by value desc
limit 1
And 2nd query will return only the single row of highest value

SQL Query to group text based on numeric column

I have a table 'TEST' as shown below
Number | Seq | Name
-------+-------+------
123 | 1 | Hello
123 | 2 | Hi
123 | 3 | Greetings
234 | 1 | Goodbye
234 | 2 | Bye
I want to write a query, to group the table by 'Number', and select the rows with the maximum sequence number (MAX(Seq)). The output of the query would be
Number | Seq | Name
-------+-------+------
123 | 3 | Greetings
234 | 2 | Bye
How do I go about this?
EDIT: TEST is actually a table that is the result from a long query (joining multiple tables) that I have already written. I already have a (SELECT ...) statement to get the values I need. Is there a way to remove duplicate rows (with the same 'Number' as shown above) and select only the one with maximum 'Seq' value.
I am on Microsoft SQL Server 2008 (SP2)
I was hoping there would be a way to achieve this by
SELECT * FROM (SELECT ...) TEST <condition to group>
You can use a select win in clause
select * from test
where (number, count) in (select number, max(count) from test group by Number)
Another option is to use a windowed ROW_NUMBER() function with a partition on the number:
With Cte As
(
Select *,
Row_Number() Over (Partition By Number Order By Count Desc) RN
From TEST
)
Select Number, Count, Name
From Cte
Where RN = 1
SELECT *
FROM (SELECT test.*, MAX (seq) OVER (PARTITION BY num) max_seq
FROM test)
WHERE seq = max_seq
I changed the column name from number because you can't use a reserved word for a column name. This is pretty much the same as the other answers, except that it explicitly gets the maximum sequence number for each NUM.
You want to use an ANALYTIC function together with a conditional clause to get you only the rows of TEST that you desire.
WITH TEST as (
...your really complex query that generates TEST...
)
SELECT
Number, Seq, Name,
RANK() OVER (PARTITION By Number ORDER BY Seq DESC) AS aRank
FROM Test
WHERE aRank = 1
;
This returns the Number, Seq, Name for each Number grouping where the Seq is maximum. Yes, it also returns a column named aRank with all '1' in it...hopefully it can be ignored.
The solution to this is to do an self join on only the MAX(Seq) values.
This answer can be found at SQL Select only rows with Max Value on a Column

How to find first duplicate row in a table sql server

I am working on SQL Server. I have a table, that contains around 75000 records. Among them there are several duplicate records. So i wrote a query to know which record repeated how many times like,
SELECT [RETAILERNAME],COUNT([RETAILERNAME]) as Repeated FROM [Stores] GROUP BY [RETAILERNAME]
It gives me result like,
---------------------------
RETAILERNAME | Repeated
---------------------------
X | 4
---------------------------
Y | 6
---------------------------
Z | 10
---------------------------
Among 4 record(s) of X record, i need take only first record of X.
so here i want to retrieve all fields from first row of duplicate records. i.e. Take all records whose RETAILERNAME='X' we will get some no. of duplicate records, we need to get only first row from them.
Please guide me.
You could try using ROW_NUMBER.
Something like
;WITH Vals AS (
SELECT [RETAILERNAME],
ROW_NUMBER() OVER(PARTITION BY [RETAILERNAME] ORDER BY [RETAILERNAME]) RowID
FROM [Stores ]
)
SELECT *
FROm Vals
WHERE RowID = 1
SQL Fiddle DEMO
You can then also remove the duplicates if need be (BUT BE CAREFUL THIS IS PERMANENT)
;WITH Vals AS (
SELECT [RETAILERNAME],
ROW_NUMBER() OVER(PARTITION BY [RETAILERNAME] ORDER BY [RETAILERNAME]) RowID
FROM Stores
)
DELETE
FROM Vals
WHERE RowID > 1;
You Can write query as under
SELECT TOP 1 * FROM [Stores] GROUP BY [RETAILERNAME]
HAVING your condition
WITH cte
AS (SELECT [retailername],
Row_number()
OVER(
partition BY [retailername]
ORDER BY [retailername])'RowRank'
FROM [retailername])
SELECT *
FROM cte