SQL Server : group by with conditon and give to function - sql

I have this table Test with a column Name in SQL Server:
Name
-----
a
a
a
c
c
b
I wrote this query:
select *
from (select Name, COUNT(*) as cnt
from Test
group by Name
having COUNT(*) > 2) as newTbl
where dbo.fn_Test(Name) = 1
Where dbo.fn_Test a SQL Server scalar function:
CREATE FUNCTION [dbo].[fn_Test]
(#name nvarchar)
RETURNS bigint
AS
BEGIN
DECLARE #count int
SET #count = (SELECT TOP 1 COUNT(*)
FROM Tbl
WHERE Name = #name);
return #count;
END
From first query FROM part is plain that this select get:
select Name, COUNT(*) as cnt
from Test
group by Name
having COUNT(*) > 2
Output:
Name cnt
--------
a 3
But when debug the query and enter to the dbo.fn_Test function it work for all names:
a b c
So how to create select in order to get only name "a" in function?

insert you first select into #t
insert into #t
select Name, COUNT(*) as cnt
from Test
group by Name
having COUNT(*) > 2)
and then use cursor to call the func
...select dbo.fn_Test(#cursor)

Try this
Select Name,Count(Name) from test
Group by Name
having Count(Name)>2

I find solution. This is my solution.
select Name, COUNT(*) as cnt
into #tmpTbl
from Tbl
group by Name
having COUNT(*) > 2
select *
from #tmpTbl
where dbo.fn_Test(Name) = 1
And in fn_Test function I get Names which is correspond to conditions.

Related

SQL(Need to print all the duplicate value IDs)

Empid----Name
1 aa
2 bb
3 cc
4 aa
5 bb
I need to get output to print EmpId number for which names are repeated
output Required:
1,2,4,5.
If you are using sql server,use the below script.
;WITH CTE_1 AS
(
SELECT *,COUNT(1)OVER(PARTITION BY Name ORDER BY Name) CNT
FROM [YourTable]
)
SELECT ID
FROM [CTE_1]
WHERE CNT > 1
Try this
select empid from table
where name in (select name from table group by name having count(*)>1)
SELECT *
FROM table AS parent
WHERE EXISTS(
SELECT *
FROM table AS sub
WHERE sub.Name == parent.Name && parent.Empid <> sub.Empid
)
Try this.
select distinct t.Empid from
#Your_Table t inner join
(
select Name, COUNT (Name) as count
from #Your_Table
group by Name
having COUNT (Name) > 1
)a on a.Name=t.Name
order by t.Empid
SELECT * FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Name) RowNo,*
From Your_Table
) a
WHERE RowNo > 1

How to update value if one of the field has multiple same values in SQL

In my database table, one of the fields has the same values. I want to change this value with random number or string which is appended to this field value for uniqueness.
Sample Data
Here 'Ma' has 5 records and so on. I want to change Name Ma01, Ma02 etc.
Id Name Count
1 Ma 5
2 Ga 6
3 Gu 5
How can do with SQL query
Try this
UPDATE TBL
SET Name = A.Name
FROM
(
SELECT
Id,
Name + CAST(ROW_NUMBER() OVER (PARTITION BY Name ORDER BY (SELECT NULL)) AS NVARCHAR(500)) AS NAME,
Count
FROM
TBL
WHERE
NAME IN
(
SELECT T.NAME FROM TBL T
GROUP BY T.NAME
HAVING COUNT(1) > 1
)
) A
WHERE
TBL.Id = A.ID
Try this:
Select Name + convert(varchar(2), row_number()over(partition by Name order by Name))
From tablename
You just try this.
Declare #i int = 1
update yourtable
set ID = #i , #i = #i + 1
Select Code based on NEER`s code with leading zero added, tested on MSSQL database.
SELECT
Id,
Name,
Name + RIGHT('00'+CAST(ROW_NUMBER() OVER (PARTITION BY Name ORDER BY (SELECT Name)) AS NVARCHAR(MAX)),2) AS Updatedname
FROM
tablename
WHERE
Name IN
(
SELECT T.NameFROM tablename T
GROUP BY T.Name
HAVING COUNT(Name) > 1
)
GROUP BY Name,Id
ORDER BY Name

Find the unique value in column MS SQL database

I have a set of data as below
number quantity
1 4
2 6
3 7
4 9
2 1
1 2
5 4
I need to find the unique value in the column "number"
The output should look like this:
number quantity
3 7
4 9
5 4
Any help would be appreciated. I am using MS SQL
In the inner query get all the distinct numbers, then join with again with the main table to get your expected results.
select o.*
from mytable o , (select number
from mytable
group by number) dist
where o.number = dist.number
One way to go could be to have an aggregate query that counts the number of occurrences for each number use it in a subquery:
SELECT number, quantity
FROM my_table
WHERE number IN (SELECT number
FROM my_table
GROUP BY number
HAVING COUNT(*) = 1)
If your column name is my_column in table my_table, the query is:
SELECT my_column, COUNT(*) as count
FROM my_table
GROUP BY my_column
HAVING COUNT(*) > 1
This will return all records that have duplicate my_column content, as well as how many times this content occurs in the database.
you can use below code for desire output:
SELECT DISTINCT(my_column), COUNT(*) as count
FROM my_table
GROUP BY my_column
Try this :
SELECT *
FROM yourtable t1
WHERE (SELECT Count(*)
FROM yourtable t2
WHERE t1.number = t2.number) = 1
Query in where clause will return number of occurrences of each number and checking it with 1 will return only those rows will have only one occurrence in table.
You can probably use ROW_NUMBER() analytic function like
select * from
(
select number,
quantity,
ROW_NUMBER() OVER(PARTITION BY number ORDER BY number) AS rn
from table1
) tab where rn = 1;
Try this:
create table #TableName(number int, quantity int)
insert into #TableName values(1, 2)
insert into #TableName values(1, 4)
insert into #TableName values(2, 4)
SELECT number, quantity
FROM #TableName
WHERE number
IN(SELECT number
FROM #TableName
GROUP BY number
HAVING COUNT(NUMBER) = 1)

Return multiple result sets AND use result set 1 to filter result set 2

/* result 1 */
select Id, Name
from Items
/* result 2 */
select Id,
Alias
from ItemAliases
where Id in (
select Id, Name
from table abc
)
We use SQL Server 2008.
Using the above example, it should be pretty straightforward what I'm trying to do.
I need to return the results of query 1... and return the results of query 2.
Query 2 however, needs to filter to only include records from result 1.
Here is my attempt to show what I would like to end up with.
VAR A = (
select Id, Name
from Items
)
/* result 1 */
select A.*
/* result 2 */
select Id,
Alias
from ItemAliases
where Id in ( A.Id )
I think you just want to store Result1 and use it to compose Result2:
declare #Result1 table (Id int primary key, Name varchar(100));
insert into #Result1
-- store Result1
select Id, Name
from Items
--return Result1
select Id, Name
from #Result1;
--return Result2 using stored Result1
select Id,
Alias
from ItemAliases
where Id in (select Id from #Result1);
--Result 1
SELECT ID, Name
FROM Items
[You WHERE Clause here if any]
--Result 2
SELECT Id, Alias
FROM ItemAliases ia
INNER JOIN Items i ON ia.ID = i.ID
OR
--Using temporay in memory table
DECLARE #abc AS TABLE (
ID AS Int,
Name AS varchar(25)
)
SELECT ID, Name
INTO #abc
FROM Items
[You WHERE Clause here if any]
--Result 1
SELECT * FROM #abc
--Result 2
SELECT Id, Alias
FROM ItemAliases ia
INNER JOIN #abc i ON ia.ID = i.ID

How to select a record if the query returns one row, or select no record if the query returns more rows?

I require to select a row if there is only one row exists, if there are more rows, it should select 0 rows.
If you're using PL/SQL, then selecting the column using select-into will throw a too_many_rows exception if there's more than one row returned:
declare
var table.column%type;
begin
select column
into var
from table
where ...;
end;
If you want to do this just using SQL, then you can do something like:
select *
from
(select s.*, count(*) over () c
from
(select *
from table
where ...
and rownum <= 2
) s
)
where c = 1
UPDATE
As DazzaL says in the comments, the reason for the rownum <= 2 restriction is to short-circuit the query if there's more than 2 rows in the result set. This can give significant performance benefits if the dataset is large.
I came up with this, just for the heck of it, using a CTE
With counter as
( select count(any_field) as cnt from your_query
)
SELECT
your_query
WHERE exists (SELECT cnt from Counter WHERE cnt=1)
1 row when there's 1 record - http://sqlfiddle.com/#!4/84c7b/2
0 rows when more than 1 rec - http://sqlfiddle.com/#!4/95c4a/1
EDIT
or if you want to avoid repeating the whole query... an example :
(using the schema from sqlfiddle http://sqlfiddle.com/#!4/6a2d8/117 )
With results as
( select * from montly_sales_totals
),
counter as
( SELECT count(name) as cnt FROM results
)
SELECT *
FROM results
WHERE exists (SELECT cnt from Counter WHERE cnt=5)
SELECT fld1, fld2
FROM (SELECT COUNT(*) over() cnt ,fld1, fld2 FROM tbl WHERE fld1 = 'key')
WHERE cnt = 1
I require to select a row if there is only one row exists, if there
are more rows, it should select 0 rows.
I assume the table contains only the row(s) you are interested to see (or not to see), in that case I would write something like
select *
from table1
where 1 = (select count(1)
from table1
)
In case you want to see only one row from a subset of results from your table, I would go for something like:
with t as ( select *
from table1
where [put here your condition]
)
select *
from t
where 1 = (select count(1)
from t
)
Try this:
SELECT f1,f2
FROM Table
WHERE (f1 = #f1) AND (f2=#f2) AND (f3=#f3)
GROUP BY f1,f2
HAVING (COUNT(*) = 1)
DECLARE COL_COUNT NUMBER;
BEGIN
COL_COUNT: = 0 ;
SELECT COUNT (1) INTO COL_COUNT FROM USER_TAB_COLUMNS WHERE TABLE_NAME = '(ur table name)';
IF COL_COUNT = 0 THEN
EXECUTE IMMEDIATE ('select * from dual') ;
END IF;
END;
Try this:
SELECT col1, col2 FROM
(SELECT count(id) as 'cnt', col1, col2 FROM table_name WHERE col1='value')
WHERE cnt=1;