Count text fields T-SQL - sql-server

Select myColumn, count(*) totalcount
from myTable
group by myColumn
having count(*) >1
order by count(*) desc;
The following works for counting integer fields, but not for text fields. How do I need to modify it so that it will work for text fields?
Thanks to all for their help!

I'm guessing you have trailing (or leading) spaces which are different values to trimmed values...
And you mean text values not datatype...

For SQL Server 2005+, you could:
SELECT CAST(myColumn AS NVARCHAR(MAX)), COUNT(*) totalcount
FROM myTable
GROUP BY CAST(myColumn AS NVARCHAR(MAX))
HAVING COUNT(*) >1
ORDER BY COUNT(*) DESC;

Related

Show single value from multiple duplicate value

I have a table in SQL Server, in this table I have a column chq_no_start with some duplicate cheque no, but the account id is different according those cheque no.
Now I want to show only one cheque no from those duplicate cheque no, no matter if one account id is missing.
I show my output:
Try this...
Select
distinct chq_no_start,
(select top 1 alt_acc_id from Table_name where chq_no_start= tn.chq_no_start order by alt_acc_id) Account_ID
From
Table_name tn
Order by
chq_no_start
Try using the DISTINCT keyword before the column name.
You could try the following:
with cte as (
select alt_acc_id, issue_date, no_of_chq, chq_no_start,
row_number() over (partition by chq_no_start order by alt_acc_id) RowNum
from your_table
where your_column = 'your_value')
select * from cte
where RowNum = 1

nested group by select in SQL Server

I am doing the following SELECT statement to see how many Reps each of my Manufacturers have in my database, this is working nicely:
SELECT ManufacturerId, COUNT(*) AS RepCount
FROM ManufacturerSalesReps WHERE IsDeleted=0
GROUP BY ManufacturerID
ORDER BY COUNT(*)
So this gives me the ManufacturerId and the number of reps but what i really need is the number of manufacturers at different rep counts. So I want to GROUP the results from the above SELECT by RepCount.
How do I accomplish this?
I cannot think of something else, but:
SELECT T.RepCount, COUNT(*) AS ManufacturerCount
FROM (
SELECT ManufacturerId, COUNT(*) AS RepCount
FROM ManufacturerSalesReps
WHERE IsDeleted=0
GROUP BY ManufacturerID
) AS T
GROUP BY T.RepCount
ORDER BY COUNT(*)
Either this is correct or totally dumb.
With windowing functions
SELECT ManufacturerId, COUNT(*),
count(ManufacturerId) over (partition by COUNT(*)) num_man AS RepCount
FROM ManufacturerSalesReps WHERE IsDeleted=0
GROUP BY ManufacturerID
ORDER BY 2

Getting a count of each distinct row in SQL Server

How do I get this statement (which returns duplicates):
Select Name from Table
To return this:
Select Distinct Name, Count(Number of non-distinct Name rows)
?
Thanks in advance.
SELECT Name, COUNT(Name) AS DistinctCount
FROM tableName
GROUP BY Name
Try:
select
Name,
count(Name)
from tableName
GROUP BY name

Generate Row Serial Numbers in SQL Query

I have a customer transaction table. I need to create a query that includes a serial number pseudo column. The serial number should be automatically reset and start over from 1 upon change in customer ID.
Now, I am familiar with the row_number() function in SQL. This doesnt exactly solve my problem because to the best of my knowledge the serial number will not be reset in case the order of the rows change.
I want to do this in a single query (SQL Server) and without having to go through any temporary table usage etc. How can this be done?
Sometime we might don't want to apply ordering on our result set to add serial number. But if we are going to use ROW_NUMBER() then we have to have a ORDER BY clause. So, for that we can simply apply a tricks to avoid any ordering on the result set.
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS ItemNo, ItemName FROM ItemMastetr
For that we don't need to apply order by on our result set. We'll just add ItemNo on our given result set.
select
ROW_NUMBER() Over (Order by CustomerID) As [S.N.],
CustomerID ,
CustomerName,
Address,
City,
State,
ZipCode
from Customers;
I'm not certain, based on your question if you want numbered rows that will remember their numbers even if the underlying data changes (and gives a different ordering), but if you just want numbered rows - that reset on a change in customer ID, then try using the Partition by clause of row_number()
row_number() over(partition by CustomerID order by CustomerID)
Implementing Serial Numbers Without Ordering Any of the Columns
Demo SQL Script-
IF OBJECT_ID('Tempdb..#TestTable') IS NOT NULL
DROP TABLE #TestTable;
CREATE TABLE #TestTable (Names VARCHAR(75), Random_No INT);
INSERT INTO #TestTable (Names,Random_No) VALUES
('Animal', 363)
,('Bat', 847)
,('Cat', 655)
,('Duet', 356)
,('Eagle', 136)
,('Frog', 784)
,('Ginger', 690);
SELECT * FROM #TestTable;
There are ‘N’ methods for implementing Serial Numbers in SQL Server. Hereby, We have mentioned the Simple Row_Number Function to generate Serial Numbers.
ROW_NUMBER() Function is one of the Window Functions that numbers all rows sequentially (for example 1, 2, 3, …) It is a temporary value that will be calculated when the query is run. It must have an OVER Clause with ORDER BY. So, we cannot able to omit Order By Clause Simply. But we can use like below-
SQL Script
IF OBJECT_ID('Tempdb..#TestTable') IS NOT NULL
DROP TABLE #TestTable;
CREATE TABLE #TestTable (Names VARCHAR(75), Random_No INT);
INSERT INTO #TestTable (Names,Random_No) VALUES
('Animal', 363)
,('Bat', 847)
,('Cat', 655)
,('Duet', 356)
,('Eagle', 136)
,('Frog', 784)
,('Ginger', 690);
SELECT Names,Random_No,ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS SERIAL_NO FROM #TestTable;
In the Above Query, We can Also Use SELECT 1, SELECT ‘ABC’, SELECT ” Instead of SELECT NULL. The result would be Same.
SELECT ROW_NUMBER() OVER (ORDER BY ColumnName1) As SrNo, ColumnName1, ColumnName2 FROM TableName
select ROW_NUMBER() over (order by pk_field ) as srno
from TableName
Using Common Table Expression (CTE)
WITH CTE AS(
SELECT ROW_NUMBER() OVER(ORDER BY CustomerId) AS RowNumber,
Customers.*
FROM Customers
)
SELECT * FROM CTE
I found one solution for MYSQL its easy to add new column for SrNo or kind of tepropery auto increment column by following this query:
SELECT #ab:=#ab+1 as SrNo, tablename.* FROM tablename, (SELECT #ab:= 0)
AS ab
ALTER function dbo.FN_ReturnNumberRows(#Start int, #End int) returns #Numbers table (Number int) as
begin
insert into #Numbers
select n = ROW_NUMBER() OVER (ORDER BY n)+#Start-1 from (
select top (#End-#Start+1) 1 as n from information_schema.columns as A
cross join information_schema.columns as B
cross join information_schema.columns as C
cross join information_schema.columns as D
cross join information_schema.columns as E) X
return
end
GO
select * from dbo.FN_ReturnNumberRows(10,9999)

select an xml type column in select query with group by SQL Server 2008

I am writing a select query in which I am fetching several columns (by joining 3-4 tables).
I use group by clause to group my results.
Query -
select ci.Candidate_Id, ci.FirstName, ci.DetailXML
from Candidate_Instance ci
where ci.Candidate_Instance_Id=2
group by
ci.Candidate_Id, ci.FirstName, ci.DetailXML
One of the tables have a column which is of XML data type. When I add the column in the select list, I get this error -
Column 'table.myXML' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
and when I add the column in the group by clause, I get this error -
The XML data type cannot be compared or sorted, except when using the IS NULL operator.
I am quite confused as to how to come out of this.
I want to get the XML data from the column.
Thanks
You cannot group by XML or TEXT columns, you would first need to convert to varchar(max)
select ci.Candidate_Id, ci.FirstName, convert(xml,convert(varchar(max),ci.DetailXML)) DetailXML
from Candidate_Instance ci
where ci.Candidate_Instance_Id=2
group by
ci.Candidate_Id, ci.FirstName, convert(varchar(max),ci.DetailXML)
On the first line, it is converted to varchar(max) to match the GROUP BY clause, and later it is re-cast back to XML.
I'm not really sure why you are using group by here based on the information in your question but anyway this whould work as it seems you are only including it in the group by in order to be able to select it.
;with cte as
(
select ci.Candidate_Id,
ci.FirstName,
ci.DetailXML,
ROW_NUMBER() OVER (PARTITION by ci.Candidate_Id, ci.FirstName ORDER BY (SELECT 0)) AS RN
from Candidate_Instance ci
where ci.Candidate_Instance_Id=2
)
SELECT Candidate_Id, FirstName, DetailXML
FROM cte
WHERE RN=1
If you have any column(s) with unique data in your table you can use a CTE, what would be a fast solution if there is an index on that column(s):
with cte as
(
select
ci.Candidate_Id,
ci.FirstName
from Candidate_Instance ci
where ci.Candidate_Instance_Id=2
group by
ci.Candidate_Id,
ci.FirstName
)
select
a.*,
b.DetailXML
from cte a
inner join Candidate_Instance b
on a.Candidate_Id = b.Candidate_Id -- <--this must be unique within Candidate_Instance

Resources