Showing posts with label rows. Show all posts
Showing posts with label rows. Show all posts

Monday, March 26, 2012

How to force 12 rows (1) per month

i have a datatable with Part , DateSold,ItemsSold

i want to show the sales for the last 12 months by month. if there were no sales for a given month i want the table to show 0.

here was my first attemp that only gives me data if all twelve months had sales.

SELECT MONTH(DateSold) AS Month, SUM(ItemsSold) AS ThisYear
FROM inv_Monthly_Sales

WHERE (YEAR(DateSold) = @.Yr - 1) AND (Part = @.Part)
GROUP BY MONTH(DateSold)
ORDER BY Month

i tried using isnull with the sum but that didn't work.

how can i force the table to always generate a dummy table of 12 months and then left join to it and in that way force it to give 12 moths of sales even when it does'n exist.

your help is greatly appreciated,

slimshim

Create a derived table that has 12 entries -- 1 for each month. Then LEFT JOIN your inv_MONTHLY_Sales table to this derived table based on the MONTH(DateSold). This will give you a row for each month.

Also, are you wanting the order that the months display to be dependent on the current month? For instance, the current month is August -- do you want the months to display Aug-Dec and then Jan-Jul? If so, you can use MONTH(getdate()) in combination with the month of the date with a MODULO operator as part of an ORDER BY.

The derived table might look something like this:

Code Snippet

select monthId
from ( select 1 as monthId union all select 2 union all
select 3 union all select 4 union all
select 5 union all select 6 union all
select 7 union all select 8 union all
select 9 union all select 10 union all
select 11 union all select 12
) as monthList
--order by monthId
order by (monthId + 12 - month(getdate())) % 12

/*
monthId
--
8
9
10
11
12
1
2
3
4
5
6
7
*/

If you don't need the top month to be the current month, just order by the "monthId" instead of the combination order that I listed.

Maybe something like:

Code Snippet

SELECT monthId AS Month,
SUM(ItemsSold) AS ThisYear
from ( select 1 as monthId union all select 2 union all
select 3 union all select 4 union all
select 5 union all select 6 union all
select 7 union all select 8 union all
select 9 union all select 10 union all
select 11 union all select 12
) as monthList
join inv_Monthly_Sales
on monthId = month(dateSold)
and (YEAR(DateSold) = @.Yr - 1)
AND (Part = @.Part)
GROUP BY monthId
ORDER BY monthId

|||I would stick to the generic order jan,feb, mar.....|||

Very well; maybe something like:

Code Snippet

SELECT monthId AS Month,
SUM(ItemsSold) AS ThisYear
from ( select 1 as monthId union all select 2 union all
select 3 union all select 4 union all
select 5 union all select 6 union all
select 7 union all select 8 union all
select 9 union all select 10 union all
select 11 union all select 12
) as monthList
join inv_Monthly_Sales
on monthId = month(dateSold)
and (YEAR(DateSold) = @.Yr - 1)
AND (Part = @.Part)
GROUP BY monthId
ORDER BY monthId

|||

THanks , I tried this code. but any year with no sales at all returns nothing. I was trying to get back all zeroes. I'm going to try it with is null on the sum and see if that works i"ll post back soon.

thanks again.

|||

I tried with isnull ... still didn't work here is the code i used. extras genereated by microsoft

SELECT monthList.monthId AS Month, ISNULL(SUM(inv_Monthly_Sales.ItemsSold), 0) AS ThisYear
FROM (SELECT 1 AS monthId
UNION ALL
SELECT 2 AS Expr1
UNION ALL
SELECT 3 AS Expr1
UNION ALL
SELECT 4 AS Expr1
UNION ALL
SELECT 5 AS Expr1
UNION ALL
SELECT 6 AS Expr1
UNION ALL
SELECT 7 AS Expr1
UNION ALL
SELECT 8 AS Expr1
UNION ALL
SELECT 9 AS Expr1
UNION ALL
SELECT 10 AS Expr1
UNION ALL
SELECT 11 AS Expr1
UNION ALL
SELECT 12 AS Expr1) AS monthList INNER JOIN
inv_Monthly_Sales ON monthList.monthId = MONTH(inv_Monthly_Sales.MonthSold) AND YEAR(inv_Monthly_Sales.MonthSold) = @.Yr AND
inv_Monthly_Sales.Part = @.Part
GROUP BY monthList.monthId
ORDER BY Month

thanks once again

|||MY FAULT! I didn't even do what I said! OH BROTHER! Change the INNER JOIN to a LEFT JOIN|||

That worked great. If no one ever told you your a genius consider it done now.Thanks again.

How can I add a Total rollup to the bottom ?

|||

Thank you for your kindness. Try adding a COMPUTE statement (I think) -- maybe add:

COMPUTE SUM(inv_Monthly_Sales.ItemsSold)

After your ORDER BY statement

|||

thnaks again . this is the error i get with the COMPUTE line added

COMPUTE clause#1,aggregare expresion #1,is not in the select list

|||

Oh, sorry; at this point I am not sure and am guessing. Maybe:

COMPUTE sum(ISNULL(SUM(inv_Monthly_Sales.ItemsSold), 0))

Will somebody please check me on this?

|||

I tried

GROUP BY monthList.monthId WITH ROLLUP

this worked except the total ended up as the first row in the result not the last.

|||

Query will return rows in any order depending on the execution plan. You need put an ORDER BY clause to get the desired order. To order results from rollup at the end, you can do below:

ORDER BY GROUPING(monthList.monthId)

|||

Thanks for the response. I tried it with that modification. here is the error message.

A Grouping function can only be specified when either CUBE or ROLLUP is specified in the GROUP BY clause|||

You might do something like this and then join as necessary:

Code Snippet

declare @.Months table(

MonthID tinyint

, MonthName varchar(9)

,MonthAbbreviation char(3)

)

declare @.dtStart datetime, @.i tinyint

select @.i =0 , @.dtStart = '01 Jan 2007'

while @.i < 12

begin

insert into @.Months

select @.i+1

, datename(MOnth,dateadd(m,@.i,@.dtSTart))

,left(datename(MOnth,dateadd(m,@.i,@.dtSTart)),3)

set @.i = @.i + 1

end

select * from @.Months

Friday, March 23, 2012

how to find which line has error

I am running a script which inserts large number of rows thru
INSERT INTO VALUES statement.
One of them is giving some error. While running it in Query Analyzer I am not able to know
which line is giving the problem. How do I make QA show me the offending line.
The script has lot of GO statements, usuall one after every 200 lines.
TIAData Cruncher wrote:
> I am running a script which inserts large number of rows thru
> INSERT INTO VALUES statement.
> One of them is giving some error. While running it in Query Analyzer
> I am not able to know which line is giving the problem. How do I make
> QA show me the offending line.
> The script has lot of GO statements, usuall one after every 200 lines.
> TIA
Try running them as separate batches; one at a time until you find the
batch with the error.
--
David Gugick
Quest Software
www.imceda.com
www.quest.com|||If you put each insert into its own batch, on error, you can just double
click on the error message in the result pane which QA should bring you to
the line that fails.
--
-oj
"Data Cruncher" <dcruncher4@.netscape.net> wrote in message
news:3g6ttvFb1038U1@.individual.net...
>I am running a script which inserts large number of rows thru INSERT INTO
>VALUES statement.
> One of them is giving some error. While running it in Query Analyzer I am
> not able to know which line is giving the problem. How do I make QA show
> me the offending line.
> The script has lot of GO statements, usuall one after every 200 lines.
> TIA

how to find which line has error

I am running a script which inserts large number of rows thru
INSERT INTO VALUES statement.
One of them is giving some error. While running it in Query Analyzer I am not able to know
which line is giving the problem. How do I make QA show me the offending line.
The script has lot of GO statements, usuall one after every 200 lines.
TIA
Data Cruncher wrote:
> I am running a script which inserts large number of rows thru
> INSERT INTO VALUES statement.
> One of them is giving some error. While running it in Query Analyzer
> I am not able to know which line is giving the problem. How do I make
> QA show me the offending line.
> The script has lot of GO statements, usuall one after every 200 lines.
> TIA
Try running them as separate batches; one at a time until you find the
batch with the error.
David Gugick
Quest Software
www.imceda.com
www.quest.com
|||If you put each insert into its own batch, on error, you can just double
click on the error message in the result pane which QA should bring you to
the line that fails.
-oj
"Data Cruncher" <dcruncher4@.netscape.net> wrote in message
news:3g6ttvFb1038U1@.individual.net...
>I am running a script which inserts large number of rows thru INSERT INTO
>VALUES statement.
> One of them is giving some error. While running it in Query Analyzer I am
> not able to know which line is giving the problem. How do I make QA show
> me the offending line.
> The script has lot of GO statements, usuall one after every 200 lines.
> TIA

how to find which line has error

I am running a script which inserts large number of rows thru
INSERT INTO VALUES statement.
One of them is giving some error. While running it in Query Analyzer I am no
t able to know
which line is giving the problem. How do I make QA show me the offending lin
e.
The script has lot of GO statements, usuall one after every 200 lines.
TIAData Cruncher wrote:
> I am running a script which inserts large number of rows thru
> INSERT INTO VALUES statement.
> One of them is giving some error. While running it in Query Analyzer
> I am not able to know which line is giving the problem. How do I make
> QA show me the offending line.
> The script has lot of GO statements, usuall one after every 200 lines.
> TIA
Try running them as separate batches; one at a time until you find the
batch with the error.
David Gugick
Quest Software
www.imceda.com
www.quest.com|||If you put each insert into its own batch, on error, you can just double
click on the error message in the result pane which QA should bring you to
the line that fails.
-oj
"Data Cruncher" <dcruncher4@.netscape.net> wrote in message
news:3g6ttvFb1038U1@.individual.net...
>I am running a script which inserts large number of rows thru INSERT INTO
>VALUES statement.
> One of them is giving some error. While running it in Query Analyzer I am
> not able to know which line is giving the problem. How do I make QA show
> me the offending line.
> The script has lot of GO statements, usuall one after every 200 lines.
> TIAsql

Wednesday, March 21, 2012

How to find the number of rows in a table

I try to find the number of rows in a table with this commands:

CountRec =

New SqlParameter
CountRec.ParameterName ="@.countrec"
CountRec.SqlDbType = SqlDbType.Int
CountRec.Value = 0

MyCommand =New Data.SqlClient.SqlCommand()
MyCommand.CommandText ="select count(*) as @.countrec from Customer;"
MyCommand.CommandType = Data.CommandType.Text
MyCommand.Connection = MyConnection
MyCommand.Parameters.Add(CountRec)
MyCommand.Connection.Open()
MyReader = MyCommand.ExecuteReader

iRecordCount = CountRec.Value

This is the result:

Incorrect syntax near '@.countrec'.

Description:An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details:System.Data.SqlClient.SqlException: Incorrect syntax near '@.countrec'.

Source Error:

Line 39: Line 40: MyCommand.Connection.Open()Line 41: MyReader = MyCommand.ExecuteReaderLine 42: iRecordCount = CountRec.ValueLine 43:


Source File:E:\Develop\Web\ASPweb\AccessTimberSales\UserEntry.aspx.vb Line:41

What to do? I need a complete example to see how it works.

Thanks...

The cause of your error is that your SQL statement should look like this:
select @.countrec = count(*) from Customer;

But you will next run into the problem that your parameter was not declared as an output parameter so its value will always contain the 0 that you assigned it, and then the further problem that output parameter values are not accessible until a data reader is closed.

There are a few different ways to achieve what you are trying to accompish. Since you only need one value, you should not be using an ExecuteReader. Try an ExecuteNonQuery instead:

CountRec =New SqlParameter


CountRec.ParameterName ="@.countrec"
CountRec.Direction = ParameterDirection.Output
CountRec.SqlDbType = SqlDbType.Int
CountRec.Value = 0

MyCommand =New Data.SqlClient.SqlCommand()
MyCommand.CommandText ="select @.countrec = count(*) from Customer;"
MyCommand.CommandType = Data.CommandType.Text
MyCommand.Connection = MyConnection
MyCommand.Parameters.Add(CountRec)
MyCommand.Connection.Open()
MyCommand.ExecuteNonQuery()

iRecordCount = CountRec.Value



Alternately, you could forget about the parameter and do an ExecuteScalar:

MyCommand =New Data.SqlClient.SqlCommand()
MyCommand.CommandText ="select count(*) from Customer;"
MyCommand.CommandType = Data.CommandType.Text
MyCommand.Connection = MyConnection
MyCommand.Connection.Open()
iRecordCount =MyCommand.ExecuteScalar()

|||

Change your query to

SELECT COUNT(*) FROM Customer

Then use an execute Scalar from your command, don't bother with the parameter.

The way you originally wrote your query doesn't return anything to the data reader...

If you've got your heart set on using the parameter make sure you set the direction to Out , then alter your query to something like:

SET @.countrec = SELECT COUNT(*) FROM Customer

|||Thanks a lot, I can use this several places.

How to find the NULL counts and non NULL counts?

Dear experts,
I am finding a LOT of rows with NULL columns in the Sybase
tables I'm querying.
Say, there is a table, with 100 rows.
25 rows are NULL
75 rows are NOT NULL.
What I'm trying to eliminate is:
select count(*)
from some_table
where fieldx is null
and then running the next query:
select count(*)
from some_table
where fieldx is NOT null
What functions can I use to run a query such as:
select count(f1( fieldx ),) AS count_of_null,
count(f2( fieldx ) ) AS count_of_not_null,
count(*)
from some_table
that would return one row that would look like:
count_of_nullcount_of_not_nullcount(*)
25 75 100
I know there is the ISNULL function. But that converts the NULL
to an actual number. Could I use other functions in conjunction with
it?
Thanks a lot!
<dba_222@.yahoo.com> wrote in message
news:1162305541.838434.188080@.f16g2000cwb.googlegr oups.com...
> Dear experts,
> I am finding a LOT of rows with NULL columns in the Sybase
> tables I'm querying.
> Say, there is a table, with 100 rows.
> 25 rows are NULL
> 75 rows are NOT NULL.
>
> What I'm trying to eliminate is:
> select count(*)
> from some_table
> where fieldx is null
> and then running the next query:
> select count(*)
> from some_table
> where fieldx is NOT null
>
> What functions can I use to run a query such as:
> select count(f1( fieldx ),) AS count_of_null,
> count(f2( fieldx ) ) AS count_of_not_null,
> count(*)
> from some_table
>
> that would return one row that would look like:
>
> count_of_null count_of_not_null count(*)
> 25 75 100
>
> I know there is the ISNULL function. But that converts the NULL
> to an actual number. Could I use other functions in conjunction with
> it?
SELECT COUNT(fieldx) AS count_of_not_null,
COUNT(*) - COUNT(fieldx) AS count_of_null
FROM some_table
Is how you would do it with MS SQL Server. Should also work with Sybase,
but I don't have a Sybase server to test on.
|||SELECT COUNT(*) as TotalRows,
COUNT(Col1) as Col1_NotNull,
COUNT(Col2) as Col2_NotNull,
COUNT(Col3) as Col3_NotNull
FROM TableWithNulls
The first column tells you the total number of rows in the table, the
other columns the number of non-nulls for the column specified. Not
that you can deal with all the columns in one SELECT.
Roy Harvey
Beacon Falls, CT
On 31 Oct 2006 06:39:01 -0800, dba_222@.yahoo.com wrote:

>Dear experts,
>I am finding a LOT of rows with NULL columns in the Sybase
>tables I'm querying.
>Say, there is a table, with 100 rows.
>25 rows are NULL
>75 rows are NOT NULL.
>
>What I'm trying to eliminate is:
>select count(*)
>from some_table
>where fieldx is null
>and then running the next query:
>select count(*)
>from some_table
>where fieldx is NOT null
>
>What functions can I use to run a query such as:
>select count(f1( fieldx ),) AS count_of_null,
>count(f2( fieldx ) ) AS count_of_not_null,
>count(*)
>from some_table
>
>that would return one row that would look like:
>
>count_of_nullcount_of_not_nullcount(*)
>25 75 100
>
>I know there is the ISNULL function. But that converts the NULL
>to an actual number. Could I use other functions in conjunction with
>it?
>
>Thanks a lot!
|||Brilliant!
I really should have thought of that.
But it was a looong tedious day yesterday.
Thanks a lot!
Mike C# wrote:
> <dba_222@.yahoo.com> wrote in message
> news:1162305541.838434.188080@.f16g2000cwb.googlegr oups.com...
> SELECT COUNT(fieldx) AS count_of_not_null,
> COUNT(*) - COUNT(fieldx) AS count_of_null
> FROM some_table
> Is how you would do it with MS SQL Server. Should also work with Sybase,
> but I don't have a Sybase server to test on.
sql

How to find the NULL counts and non NULL counts?

Dear experts,
I am finding a LOT of rows with NULL columns in the Sybase
tables I'm querying.
Say, there is a table, with 100 rows.
25 rows are NULL
75 rows are NOT NULL.
What I'm trying to eliminate is:
select count(*)
from some_table
where fieldx is null
and then running the next query:
select count(*)
from some_table
where fieldx is NOT null
What functions can I use to run a query such as:
select count(f1( fieldx ),) AS count_of_null,
count(f2( fieldx ) ) AS count_of_not_null,
count(*)
from some_table
that would return one row that would look like:
count_of_null count_of_not_null count(*)
25 75 100
I know there is the ISNULL function. But that converts the NULL
to an actual number. Could I use other functions in conjunction with
it?
Thanks a lot!<dba_222@.yahoo.com> wrote in message
news:1162305541.838434.188080@.f16g2000cwb.googlegroups.com...
> Dear experts,
> I am finding a LOT of rows with NULL columns in the Sybase
> tables I'm querying.
> Say, there is a table, with 100 rows.
> 25 rows are NULL
> 75 rows are NOT NULL.
>
> What I'm trying to eliminate is:
> select count(*)
> from some_table
> where fieldx is null
> and then running the next query:
> select count(*)
> from some_table
> where fieldx is NOT null
>
> What functions can I use to run a query such as:
> select count(f1( fieldx ),) AS count_of_null,
> count(f2( fieldx ) ) AS count_of_not_null,
> count(*)
> from some_table
>
> that would return one row that would look like:
>
> count_of_null count_of_not_null count(*)
> 25 75 100
>
> I know there is the ISNULL function. But that converts the NULL
> to an actual number. Could I use other functions in conjunction with
> it?
SELECT COUNT(fieldx) AS count_of_not_null,
COUNT(*) - COUNT(fieldx) AS count_of_null
FROM some_table
Is how you would do it with MS SQL Server. Should also work with Sybase,
but I don't have a Sybase server to test on.|||SELECT COUNT(*) as TotalRows,
COUNT(Col1) as Col1_NotNull,
COUNT(Col2) as Col2_NotNull,
COUNT(Col3) as Col3_NotNull
FROM TableWithNulls
The first column tells you the total number of rows in the table, the
other columns the number of non-nulls for the column specified. Not
that you can deal with all the columns in one SELECT.
Roy Harvey
Beacon Falls, CT
On 31 Oct 2006 06:39:01 -0800, dba_222@.yahoo.com wrote:

>Dear experts,
>I am finding a LOT of rows with NULL columns in the Sybase
>tables I'm querying.
>Say, there is a table, with 100 rows.
>25 rows are NULL
>75 rows are NOT NULL.
>
>What I'm trying to eliminate is:
>select count(*)
>from some_table
>where fieldx is null
>and then running the next query:
>select count(*)
>from some_table
>where fieldx is NOT null
>
>What functions can I use to run a query such as:
>select count(f1( fieldx ),) AS count_of_null,
> count(f2( fieldx ) ) AS count_of_not_null,
> count(*)
>from some_table
>
>that would return one row that would look like:
>
> count_of_null count_of_not_null count(*)
>25 75 100
>
>I know there is the ISNULL function. But that converts the NULL
>to an actual number. Could I use other functions in conjunction with
>it?
>
>Thanks a lot!|||Brilliant!
I really should have thought of that.
But it was a looong tedious day yesterday.
Thanks a lot!
Mike C# wrote:
> <dba_222@.yahoo.com> wrote in message
> news:1162305541.838434.188080@.f16g2000cwb.googlegroups.com...
> SELECT COUNT(fieldx) AS count_of_not_null,
> COUNT(*) - COUNT(fieldx) AS count_of_null
> FROM some_table
> Is how you would do it with MS SQL Server. Should also work with Sybase,
> but I don't have a Sybase server to test on.

How to find the NULL counts and non NULL counts?

Dear experts,
I am finding a LOT of rows with NULL columns in the Sybase
tables I'm querying.
Say, there is a table, with 100 rows.
25 rows are NULL
75 rows are NOT NULL.
What I'm trying to eliminate is:
select count(*)
from some_table
where fieldx is null
and then running the next query:
select count(*)
from some_table
where fieldx is NOT null
What functions can I use to run a query such as:
select count(f1( fieldx ),) AS count_of_null,
count(f2( fieldx ) ) AS count_of_not_null,
count(*)
from some_table
that would return one row that would look like:
count_of_null count_of_not_null count(*)
25 75 100
I know there is the ISNULL function. But that converts the NULL
to an actual number. Could I use other functions in conjunction with
it?
Thanks a lot!<dba_222@.yahoo.com> wrote in message
news:1162305541.838434.188080@.f16g2000cwb.googlegroups.com...
> Dear experts,
> I am finding a LOT of rows with NULL columns in the Sybase
> tables I'm querying.
> Say, there is a table, with 100 rows.
> 25 rows are NULL
> 75 rows are NOT NULL.
>
> What I'm trying to eliminate is:
> select count(*)
> from some_table
> where fieldx is null
> and then running the next query:
> select count(*)
> from some_table
> where fieldx is NOT null
>
> What functions can I use to run a query such as:
> select count(f1( fieldx ),) AS count_of_null,
> count(f2( fieldx ) ) AS count_of_not_null,
> count(*)
> from some_table
>
> that would return one row that would look like:
>
> count_of_null count_of_not_null count(*)
> 25 75 100
>
> I know there is the ISNULL function. But that converts the NULL
> to an actual number. Could I use other functions in conjunction with
> it?
SELECT COUNT(fieldx) AS count_of_not_null,
COUNT(*) - COUNT(fieldx) AS count_of_null
FROM some_table
Is how you would do it with MS SQL Server. Should also work with Sybase,
but I don't have a Sybase server to test on.|||SELECT COUNT(*) as TotalRows,
COUNT(Col1) as Col1_NotNull,
COUNT(Col2) as Col2_NotNull,
COUNT(Col3) as Col3_NotNull
FROM TableWithNulls
The first column tells you the total number of rows in the table, the
other columns the number of non-nulls for the column specified. Not
that you can deal with all the columns in one SELECT.
Roy Harvey
Beacon Falls, CT
On 31 Oct 2006 06:39:01 -0800, dba_222@.yahoo.com wrote:
>Dear experts,
>I am finding a LOT of rows with NULL columns in the Sybase
>tables I'm querying.
>Say, there is a table, with 100 rows.
>25 rows are NULL
>75 rows are NOT NULL.
>
>What I'm trying to eliminate is:
>select count(*)
>from some_table
>where fieldx is null
>and then running the next query:
>select count(*)
>from some_table
>where fieldx is NOT null
>
>What functions can I use to run a query such as:
>select count(f1( fieldx ),) AS count_of_null,
> count(f2( fieldx ) ) AS count_of_not_null,
> count(*)
>from some_table
>
>that would return one row that would look like:
>
>count_of_null count_of_not_null count(*)
>25 75 100
>
>I know there is the ISNULL function. But that converts the NULL
>to an actual number. Could I use other functions in conjunction with
>it?
>
>Thanks a lot!|||Brilliant!
I really should have thought of that.
But it was a looong tedious day yesterday.
Thanks a lot!
Mike C# wrote:
> <dba_222@.yahoo.com> wrote in message
> news:1162305541.838434.188080@.f16g2000cwb.googlegroups.com...
> > Dear experts,
> >
> > I am finding a LOT of rows with NULL columns in the Sybase
> > tables I'm querying.
> >
> > Say, there is a table, with 100 rows.
> > 25 rows are NULL
> > 75 rows are NOT NULL.
> >
> >
> > What I'm trying to eliminate is:
> >
> > select count(*)
> > from some_table
> > where fieldx is null
> >
> > and then running the next query:
> >
> > select count(*)
> > from some_table
> > where fieldx is NOT null
> >
> >
> > What functions can I use to run a query such as:
> >
> > select count(f1( fieldx ),) AS count_of_null,
> > count(f2( fieldx ) ) AS count_of_not_null,
> > count(*)
> > from some_table
> >
> >
> > that would return one row that would look like:
> >
> >
> > count_of_null count_of_not_null count(*)
> >
> > 25 75 100
> >
> >
> >
> > I know there is the ISNULL function. But that converts the NULL
> > to an actual number. Could I use other functions in conjunction with
> > it?
> SELECT COUNT(fieldx) AS count_of_not_null,
> COUNT(*) - COUNT(fieldx) AS count_of_null
> FROM some_table
> Is how you would do it with MS SQL Server. Should also work with Sybase,
> but I don't have a Sybase server to test on.

How to find the duplicate value

I want to set a filed to primary key.
But there duplicate value in it.
How can I find all rows with the duplicate value of that field?
ad
Itzik Ben-Gan written a greate examples about that
CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)
PRINT 'Table'
SELECT * FROM #Demo
PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Cleaned-up Table'
SELECT * FROM #Demo
DROP TABLE #Demo
"ad" <ad@.wfes.tcc.edu.tw> wrote in message
news:%23AKUV72MFHA.1176@.TK2MSFTNGP15.phx.gbl...
> I want to set a filed to primary key.
> But there duplicate value in it.
> How can I find all rows with the duplicate value of that field?
>
|||Hi
If the whole row is duplicated then you can create a temporary table with
the same structure that is populated with
INSERT INTO #tmp SELECT DISTINCT * FROM MyTable
you can then
TRUNCATE MyTable
and re-insert the value back
INSERT INTO MyTable SELECT * FROM #tmp
If this is not the case, then you will need to differentiate the records
somehow and then choose one to keep e.g. If there say a datetime column
called date_created and you wish to keep the earliest and you primary key is
a column(s) called PK then (assuming date_created is unique for each pk)
DELETE FROM MyTable
FROM MyTable t
WHERE t.date_created > ( SELECT MIN(date_created) FROM MyTable M where m.pk
= t.pk )
John
"ad" <ad@.wfes.tcc.edu.tw> wrote in message
news:%23AKUV72MFHA.1176@.TK2MSFTNGP15.phx.gbl...
>I want to set a filed to primary key.
> But there duplicate value in it.
> How can I find all rows with the duplicate value of that field?
>
|||On Mon, 28 Mar 2005 16:19:13 +0800, ad wrote:

>I want to set a filed to primary key.
>But there duplicate value in it.
>How can I find all rows with the duplicate value of that field?
>
Hi ad,
For just finding the duplicate key values:
SELECT KeyColumn, COUNT(*)
FROM MyTable
GROUP BY KeyColumn
HAVING COUNT(*)
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)
|||Hugo left out a little part on his query... on the having clause
For just finding the duplicate key values:
SELECT KeyColumn, COUNT(*)
FROM MyTable
GROUP BY KeyColumn
HAVING COUNT(*) > 1
Wayne Snyder, MCDBA, SQL Server MVP
Mariner, Charlotte, NC
www.mariner-usa.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
"ad" <ad@.wfes.tcc.edu.tw> wrote in message
news:%23AKUV72MFHA.1176@.TK2MSFTNGP15.phx.gbl...
>I want to set a filed to primary key.
> But there duplicate value in it.
> How can I find all rows with the duplicate value of that field?
>
|||On Mon, 28 Mar 2005 08:26:42 -0500, Wayne Snyder wrote:

>Hugo left out a little part on his query... on the having clause
Ouch! Thanks for catching that, Wayne!
Best, Hugo
(Remove _NO_ and _SPAM_ to get my e-mail address)

How to find the duplicate value

I want to set a filed to primary key.
But there duplicate value in it.
How can I find all rows with the duplicate value of that field?ad
Itzik Ben-Gan written a greate examples about that
CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)
PRINT 'Table'
SELECT * FROM #Demo
PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Cleaned-up Table'
SELECT * FROM #Demo
DROP TABLE #Demo
"ad" <ad@.wfes.tcc.edu.tw> wrote in message
news:%23AKUV72MFHA.1176@.TK2MSFTNGP15.phx.gbl...
> I want to set a filed to primary key.
> But there duplicate value in it.
> How can I find all rows with the duplicate value of that field?
>|||Hi
If the whole row is duplicated then you can create a temporary table with
the same structure that is populated with
INSERT INTO #tmp SELECT DISTINCT * FROM MyTable
you can then
TRUNCATE MyTable
and re-insert the value back
INSERT INTO MyTable SELECT * FROM #tmp
If this is not the case, then you will need to differentiate the records
somehow and then choose one to keep e.g. If there say a datetime column
called date_created and you wish to keep the earliest and you primary key is
a column(s) called PK then (assuming date_created is unique for each pk)
DELETE FROM MyTable
FROM MyTable t
WHERE t.date_created > ( SELECT MIN(date_created) FROM MyTable M where m.pk
= t.pk )
John
"ad" <ad@.wfes.tcc.edu.tw> wrote in message
news:%23AKUV72MFHA.1176@.TK2MSFTNGP15.phx.gbl...
>I want to set a filed to primary key.
> But there duplicate value in it.
> How can I find all rows with the duplicate value of that field?
>|||On Mon, 28 Mar 2005 16:19:13 +0800, ad wrote:

>I want to set a filed to primary key.
>But there duplicate value in it.
>How can I find all rows with the duplicate value of that field?
>
Hi ad,
For just finding the duplicate key values:
SELECT KeyColumn, COUNT(*)
FROM MyTable
GROUP BY KeyColumn
HAVING COUNT(*)
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hugo left out a little part on his query... on the having clause
For just finding the duplicate key values:
SELECT KeyColumn, COUNT(*)
FROM MyTable
GROUP BY KeyColumn
HAVING COUNT(*) > 1
Wayne Snyder, MCDBA, SQL Server MVP
Mariner, Charlotte, NC
www.mariner-usa.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
"ad" <ad@.wfes.tcc.edu.tw> wrote in message
news:%23AKUV72MFHA.1176@.TK2MSFTNGP15.phx.gbl...
>I want to set a filed to primary key.
> But there duplicate value in it.
> How can I find all rows with the duplicate value of that field?
>|||On Mon, 28 Mar 2005 08:26:42 -0500, Wayne Snyder wrote:

>Hugo left out a little part on his query... on the having clause
Ouch! Thanks for catching that, Wayne!
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

Monday, March 19, 2012

How to find the duplicate value

I want to set a filed to primary key.
But there duplicate value in it.
How can I find all rows with the duplicate value of that field?ad
Itzik Ben-Gan written a greate examples about that
CREATE TABLE #Demo (
idNo int identity(1,1),
colA int,
colB int
)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (1,6)
INSERT INTO #Demo(colA,colB) VALUES (2,4)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (4,2)
INSERT INTO #Demo(colA,colB) VALUES (3,3)
INSERT INTO #Demo(colA,colB) VALUES (5,1)
INSERT INTO #Demo(colA,colB) VALUES (8,1)
PRINT 'Table'
SELECT * FROM #Demo
PRINT 'Duplicates in Table'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo <> B.idNo
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Duplicates to Delete'
SELECT * FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
DELETE FROM #Demo
WHERE idNo IN
(SELECT B.idNo
FROM #Demo A JOIN #Demo B
ON A.idNo < B.idNo -- < this time, not <>
AND A.colA = B.colA
AND A.colB = B.colB)
PRINT 'Cleaned-up Table'
SELECT * FROM #Demo
DROP TABLE #Demo
"ad" <ad@.wfes.tcc.edu.tw> wrote in message
news:%23AKUV72MFHA.1176@.TK2MSFTNGP15.phx.gbl...
> I want to set a filed to primary key.
> But there duplicate value in it.
> How can I find all rows with the duplicate value of that field?
>|||Hi
If the whole row is duplicated then you can create a temporary table with
the same structure that is populated with
INSERT INTO #tmp SELECT DISTINCT * FROM MyTable
you can then
TRUNCATE MyTable
and re-insert the value back
INSERT INTO MyTable SELECT * FROM #tmp
If this is not the case, then you will need to differentiate the records
somehow and then choose one to keep e.g. If there say a datetime column
called date_created and you wish to keep the earliest and you primary key is
a column(s) called PK then (assuming date_created is unique for each pk)
DELETE FROM MyTable
FROM MyTable t
WHERE t.date_created > ( SELECT MIN(date_created) FROM MyTable M where m.pk
= t.pk )
John
"ad" <ad@.wfes.tcc.edu.tw> wrote in message
news:%23AKUV72MFHA.1176@.TK2MSFTNGP15.phx.gbl...
>I want to set a filed to primary key.
> But there duplicate value in it.
> How can I find all rows with the duplicate value of that field?
>|||On Mon, 28 Mar 2005 16:19:13 +0800, ad wrote:
>I want to set a filed to primary key.
>But there duplicate value in it.
>How can I find all rows with the duplicate value of that field?
>
Hi ad,
For just finding the duplicate key values:
SELECT KeyColumn, COUNT(*)
FROM MyTable
GROUP BY KeyColumn
HAVING COUNT(*)
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||Hugo left out a little part on his query... on the having clause
For just finding the duplicate key values:
SELECT KeyColumn, COUNT(*)
FROM MyTable
GROUP BY KeyColumn
HAVING COUNT(*) > 1
Wayne Snyder, MCDBA, SQL Server MVP
Mariner, Charlotte, NC
www.mariner-usa.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
"ad" <ad@.wfes.tcc.edu.tw> wrote in message
news:%23AKUV72MFHA.1176@.TK2MSFTNGP15.phx.gbl...
>I want to set a filed to primary key.
> But there duplicate value in it.
> How can I find all rows with the duplicate value of that field?
>|||On Mon, 28 Mar 2005 08:26:42 -0500, Wayne Snyder wrote:
>Hugo left out a little part on his query... on the having clause
Ouch! Thanks for catching that, Wayne!
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

How to find rows marked for replication?

SQL Server 2005
Someone here attempted to update about 3000 rows in a table that is in
replication (on the publisher side). We are using push replication.
The rows were updated successfully on the publisher table, but for some
reason, it serioulsy locked up the replicated table on the subscriber
side. Because of the locking problem, none of the rows actually got
updated on the subscriber side.
At this point, the DBA turned off replication to release the locks on
the table (which it did).
So, now the situation is, there's a bunch of rows marked for
replication that haven't yet been successfully replicated. My question
is, is there a way to "undo" the changes? If so, how would one do this.
The other option is to turn replication on later tonight when no users
are online, I suppose.
Has anyone else had this problem and how did you solve it?
Thanks
Are you using transactional replication? If so, then please try using
sp_browsereplcmds. If you are using merge, then you could try my routine
(http://www.replicationanswers.com/Script9.asp).
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .
|||Yes, thank you
This information also corresponds to the number of rows in the
"msrepl_commands" table.
I was told that I can simply truncate the msrepl_commands table to
clear the slate, so to speak. Is this correct? And will it hurt
anything?
Paul Ibison wrote:
> Are you using transactional replication? If so, then please try using
> sp_browsereplcmds. If you are using merge, then you could try my routine
> (http://www.replicationanswers.com/Script9.asp).
> Cheers,
> Paul Ibison SQL Server MVP, www.replicationanswers.com .
|||This sort of thing is possible - after all it is essentially what the
cleanup agent does. However you'll also need to take into account
msrepl_transactions, and be sure to delete only relevant commands ie not
ones belonging to other articles or publications and finally you'll be
creating a situation of non-convergence which might lead to synchronization
errors later on. All this is taking you into unsupported territory so I'd
recommend simply synchronizing during a quiet time.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .

How to find rows marked for replication?

SQL Server 2005
Someone here attempted to update about 3000 rows in a table that is in
replication (on the publisher side). We are using push replication.
The rows were updated successfully on the publisher table, but for some
reason, it serioulsy locked up the replicated table on the subscriber
side. Because of the locking problem, none of the rows actually got
updated on the subscriber side.
At this point, the DBA turned off replication to release the locks on
the table (which it did).
So, now the situation is, there's a bunch of rows marked for
replication that haven't yet been successfully replicated. My question
is, is there a way to "undo" the changes? If so, how would one do this.
The other option is to turn replication on later tonight when no users
are online, I suppose.
Has anyone else had this problem and how did you solve it?
ThanksAre you using transactional replication? If so, then please try using
sp_browsereplcmds. If you are using merge, then you could try my routine
(http://www.replicationanswers.com/Script9.asp).
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .|||Yes, thank you
This information also corresponds to the number of rows in the
"msrepl_commands" table.
I was told that I can simply truncate the msrepl_commands table to
clear the slate, so to speak. Is this correct? And will it hurt
anything?
Paul Ibison wrote:
> Are you using transactional replication? If so, then please try using
> sp_browsereplcmds. If you are using merge, then you could try my routine
> (http://www.replicationanswers.com/Script9.asp).
> Cheers,
> Paul Ibison SQL Server MVP, www.replicationanswers.com .|||This sort of thing is possible - after all it is essentially what the
cleanup agent does. However you'll also need to take into account
msrepl_transactions, and be sure to delete only relevant commands ie not
ones belonging to other articles or publications and finally you'll be
creating a situation of non-convergence which might lead to synchronization
errors later on. All this is taking you into unsupported territory so I'd
recommend simply synchronizing during a quiet time.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .

How to find rows marked for replication?

SQL Server 2005
Someone here attempted to update about 3000 rows in a table that is in
replication (on the publisher side). We are using push replication.
The rows were updated successfully on the publisher table, but for some
reason, it serioulsy locked up the replicated table on the subscriber
side. Because of the locking problem, none of the rows actually got
updated on the subscriber side.
At this point, the DBA turned off replication to release the locks on
the table (which it did).
So, now the situation is, there's a bunch of rows marked for
replication that haven't yet been successfully replicated. My question
is, is there a way to "undo" the changes? If so, how would one do this.
The other option is to turn replication on later tonight when no users
are online, I suppose.
Has anyone else had this problem and how did you solve it?
ThanksAre you using transactional replication? If so, then please try using
sp_browsereplcmds. If you are using merge, then you could try my routine
(http://www.replicationanswers.com/Script9.asp).
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .|||Yes, thank you
This information also corresponds to the number of rows in the
"msrepl_commands" table.
I was told that I can simply truncate the msrepl_commands table to
clear the slate, so to speak. Is this correct? And will it hurt
anything?
Paul Ibison wrote:
> Are you using transactional replication? If so, then please try using
> sp_browsereplcmds. If you are using merge, then you could try my routine
> (http://www.replicationanswers.com/Script9.asp).
> Cheers,
> Paul Ibison SQL Server MVP, www.replicationanswers.com .|||This sort of thing is possible - after all it is essentially what the
cleanup agent does. However you'll also need to take into account
msrepl_transactions, and be sure to delete only relevant commands ie not
ones belonging to other articles or publications and finally you'll be
creating a situation of non-convergence which might lead to synchronization
errors later on. All this is taking you into unsupported territory so I'd
recommend simply synchronizing during a quiet time.
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com .

Monday, March 12, 2012

How to find out what rows are not in a table

Hi

I have a problem where I must compair an import table with a local datatable and import rows that are missing and correct the rows that are different.

How to best do this?

I was hoping to avoid cursors

thanks

Walter

hi

what is simple is just refer to the database

and get the rows from current db and insert the sam in target database

use not in clause in source Db so u can take out the duplicates

I hope u ll be geting it right

TechiTawa

|||

walter_verhoeven wrote:

Hi

I have a problem where I must compair an import table with a local datatable and import rows that are missing and correct the rows that are different.

How to best do this?

I was hoping to avoid cursors

thanks

Walter

you need an upsert (update /insert) statement

unfortunately upsert is not a supported keyowrd in sql server right now but

there are work around.

see this links

http://sudheerpalyam.spaces.live.com/Blog/cns!1pKCMhBsSwPMevqFfdi-3JgQ!198.entry

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=58353

Wednesday, March 7, 2012

How to find max from a table by row

I have a Product table with the columns

AcctNum
ProdCode
InvoiceDate

I can have multiple rows for a given AcctNum:

123 A 01/01/2005
123 B 01/02/2005
123 C 01/03/2005
234 C 02/01/2004
345 A 01/01/2005
345 B 01/02/2005

I need the max(InvoiceDate) and if the max for a given AcctNum is a ProdCode
= B. So if the latest InvoiceDate is for a given AcctNum is B then return
that row.

123 B 01/02/2005
Would not be returned because the max Invoice date for AcctNum 123 is
ProdCode C.

345 B 01/02/2005
Would be returned because the max Invoice date for AcctNum 345 is ProdCode
B.

I can solve this using a cursor fairly easily by using a distinct AcctNum in
the cursor select and getting the max InvoiceDate for each AcctNum. This is
a costly and I'm looking for a solution using temp tables or a query to
handle this problem.

I hope I have made this clear enough (sorry if I was too verbose). Thanks in
advance for your help.

-pHi

Try

SELECT A.AcctNum, A.ProdCode, A.InvoiceDate
FROM MyAccts A
WHERE ProdCode = 'B'
AND NOT EXISTS ( SELECT 1 FROM MyAccts B WHERE A.AcctNum = B.AcctNum AND
B.InvoiceDate > A.InvoiceDate )

or

SELECT A.AcctNum, A.ProdCode, A.InvoiceDate
FROM MyAccts A
WHERE ProdCode = 'B'
AND A.InvoiceDate = ( SELECT MAX(B.InvoiceDate) FROM MyAccts B WHERE
A.AcctNum = B.AcctNum )

Also check out how to post DDL and example data at
http://www.aspfaq.com/etiquett*e.asp?id=5006 and
example data as insert statements http://vyaskn.tripod.com/code.*htm#inserts
It is also useful to post your current attempts at solving the problem.

John
"Pippen" <name@.notreal.add> wrote in message
news:O9GdnTvxA-1jPqHfRVn-iw@.comcast.com...
>I have a Product table with the columns
> AcctNum
> ProdCode
> InvoiceDate
> I can have multiple rows for a given AcctNum:
> 123 A 01/01/2005
> 123 B 01/02/2005
> 123 C 01/03/2005
> 234 C 02/01/2004
> 345 A 01/01/2005
> 345 B 01/02/2005
> I need the max(InvoiceDate) and if the max for a given AcctNum is a
> ProdCode = B. So if the latest InvoiceDate is for a given AcctNum is B
> then return that row.
> 123 B 01/02/2005
> Would not be returned because the max Invoice date for AcctNum 123 is
> ProdCode C.
> 345 B 01/02/2005
> Would be returned because the max Invoice date for AcctNum 345 is ProdCode
> B.
> I can solve this using a cursor fairly easily by using a distinct AcctNum
> in the cursor select and getting the max InvoiceDate for each AcctNum.
> This is a costly and I'm looking for a solution using temp tables or a
> query to handle this problem.
> I hope I have made this clear enough (sorry if I was too verbose). Thanks
> in advance for your help.
> -p
>|||"John Bell" <jbellnewsposts@.hotmail.com> wrote in message
news:423d73a3$0$32610$db0fefd9@.news.zen.co.uk...
> Hi
> Try
> SELECT A.AcctNum, A.ProdCode, A.InvoiceDate
> FROM MyAccts A
> WHERE ProdCode = 'B'
> AND NOT EXISTS ( SELECT 1 FROM MyAccts B WHERE A.AcctNum = B.AcctNum AND
> B.InvoiceDate > A.InvoiceDate )
> or
> SELECT A.AcctNum, A.ProdCode, A.InvoiceDate
> FROM MyAccts A
> WHERE ProdCode = 'B'
> AND A.InvoiceDate = ( SELECT MAX(B.InvoiceDate) FROM MyAccts B WHERE
> A.AcctNum = B.AcctNum )
> Also check out how to post DDL and example data at
> http://www.aspfaq.com/etiquett*e.asp?id=5006 and
> example data as insert statements
> http://vyaskn.tripod.com/code.*htm#inserts
> It is also useful to post your current attempts at solving the problem.
> John
> "Pippen" <name@.notreal.add> wrote in message
> news:O9GdnTvxA-1jPqHfRVn-iw@.comcast.com...
>>I have a Product table with the columns
>>
>> AcctNum
>> ProdCode
>> InvoiceDate
>>
>> I can have multiple rows for a given AcctNum:
>>
>> 123 A 01/01/2005
>> 123 B 01/02/2005
>> 123 C 01/03/2005
>> 234 C 02/01/2004
>> 345 A 01/01/2005
>> 345 B 01/02/2005
>>
>> I need the max(InvoiceDate) and if the max for a given AcctNum is a
>> ProdCode = B. So if the latest InvoiceDate is for a given AcctNum is B
>> then return that row.
>>
>> 123 B 01/02/2005
>> Would not be returned because the max Invoice date for AcctNum 123 is
>> ProdCode C.
>>
>> 345 B 01/02/2005
>> Would be returned because the max Invoice date for AcctNum 345 is
>> ProdCode B.
>>
>> I can solve this using a cursor fairly easily by using a distinct AcctNum
>> in the cursor select and getting the max InvoiceDate for each AcctNum.
>> This is a costly and I'm looking for a solution using temp tables or a
>> query to handle this problem.
>>
>> I hope I have made this clear enough (sorry if I was too verbose). Thanks
>> in advance for your help.
>>
>> -p
>
Thanks for the help.

-p

How to find duplicate rows?

How can I find the duplicate rows in a table?
Thanks.
LaEsmeralda
select [field1],[field2]
from YourTable
group by [field1],[field2]
having count(*) > 1
http://sqlservercode.blogspot.com/

How to find duplicate rows?

How can I find the duplicate rows in a table?
Thanks.
LaEsmeraldaselect [field1],[field2]
from YourTable
group by [field1],[field2]
having count(*) > 1
http://sqlservercode.blogspot.com/

How to find duplicate rows?

How can I find the duplicate rows in a table?
Thanks.
LaEsmeraldaselect [field1],[field2]
from YourTable
group by [field1],[field2]
having count(*) > 1
http://sqlservercode.blogspot.com/

How to find duplicate rows in SQL server

I would like to locate duplicate rows within a specific table. This table has 12 diffrent rows.

BASENO - POSITION - SEQ - PROD -STYL - DESCR - FIELD01 THRU FIELD05 - VALUE01 THRU VALUE05 - FORMTYPE - ANSWER

I have been playing with the following query but can't seem to get it perfect to locate my dups within sql. Can someone help me with the querry?

I'm playing with the following querry.
SELECT
<list of all columns>
FROM
tablename
GROUP BY
<list of all columns>
HAVING
Count(*) > 1

Can somone possible input my column names into this querry that would possibly get it to locate my dups? I'm missing somehting and not sure what.

Thanks for any help

SQL NewbieIf you simply want to eliminate all of the rows that have a duplicate (every one of them, leaving none behind at all), you can use:DELETE FROM tablename
WHERE 1 < (SELECT Count(*)
FROM tablename AS z
WHERE z.baseno = tablename.baseno
AND z.position = tablename.position
-- continue for all columns
)This is rarely what people want, since they usually want to keep one of the rows. That is a tougher challenge.

-PatP|||I had a situation where I needed to delete the duplicate values (there may be more than one) and keep the minimum (or first) value. Assuming you have an id value and BRANCHNO is your duplicate field:

SELECT id
FROM tablename
WHERE id
IN (SELECT a.id
FROM tablename AS a, tablename AS b
WHERE a.BRANCHNO = b.BRANCHNO
AND a.id > b.id);

Not 100% sure but give it a shot.

ddave|||To simply identify the duplicated values, this is the syntax:

SELECT BASENO, POSITION, SEQ, PROD, STYL, DESCR, FIELD01, FIELD02, FIELD03, FIELD04, FIELD05, VALUE01, VALUE02, VALUE03, VALUE04, VALUE05, FORMTYPE, ANSWER
FROM tablename
GROUP BY
BASENO, POSITION, SEQ, PROD, STYL, DESCR, FIELD01, FIELD02, FIELD03, FIELD04, FIELD05, VALUE01, VALUE02, VALUE03, VALUE04, VALUE05, FORMTYPE, ANSWER
HAVING Count(*) > 1|||Ooops, my bad. I misread the question thinking that you wanted to DELETE the rows, not just see them. Sorry.

-PatP|||If you simply want to eliminate all of the rows that have a duplicate (every one of them, leaving none behind at all), you can use:DELETE FROM tablename
WHERE 1 < (SELECT Count(*)
FROM tablename AS z
WHERE z.baseno = tablename.baseno
AND z.position = tablename.position
-- continue for all columns
)This is rarely what people want, since they usually want to keep one of the rows. That is a tougher challenge.

-PatP

I used your information above and I recieved a relply that (0 row(s) affected).
However when I try and set my primary keys and allow NUULS options I get an error message about duplicates. (below)

'TableName' table
-unable to create index 'PK_TableName'.
ODBC error CREATE UNIQUE INDEX terminated because a duplicate key was found for index ID 1. Most significant primary key is 415162|||Ah, that is quite differentthan the original question though. Now you want to find duplicates based on just the PK column(s)!

To find the rows with duplicate key values, you need to use something like:SELECT pk_col1, pk_col2, pk_colN
FROM tablename
WHERE 1 < (SELECT Count(*)
FROM tablename AS z
WHERE z.pk_col1 = tablename.pk_col1
AND z.pk_col2 = tablename.pk_col2
AND z.pk_colN = tablename.pk_colN)Which column(s) are your candidate key?

-PatP|||Ah, that is quite differentthan the original question though. Now you want to find duplicates based on just the PK column(s)!

To find the rows with duplicate key values, you need to use something like:SELECT pk_col1, pk_col2, pk_colN
FROM tablename
WHERE 1 < (SELECT Count(*)
FROM tablename AS z
WHERE z.pk_col1 = tablename.pk_col1
AND z.pk_col2 = tablename.pk_col2
AND z.pk_colN = tablename.pk_colN)Which column(s) are your candidate key?

-PatP

Thanks for your help. I really appreciate your time. i will give it a try.