Showing posts with label column. Show all posts
Showing posts with label column. Show all posts

Thursday, March 29, 2012

count records in several months

Hi,

I've a small problem. I have a table in which one column is date. I want to
count the records for statiscs in a temptable grouped by months lets say 12
months back.
e.g.
month 1 counts 164 rec month 2 counts 87 records and so on.
I tried to solve this like this with a function SELECT COUNT(*) FROM TABLE
WHERE DATEDIFF(m,Col1,GETDATE())=@.counter.
But I don't know how to get this thing count from 0 up to 11 to get this
thing recursive.
Does anyone know how to tackel my problem? I wouls apreciate any answer.
Greetz to you allYou need counts based on months? If your date column is datetime datatype,
something like this could work:

select count(*) as No, month(col1) as month, year (col1) as year
from table
where datediff(m, col1, getdate()) <= 12 -- if you want only last 12 months
group by month(col1) as month, year (col1) as year

If you posted create statements and some sample data I could test this...

MC

"Sjef ten Koppel" <sjeftenkoppel@.home.nlwrote in message
news:er97ad$qkb$1@.news6.zwoll1.ov.home.nl...

Quote:

Originally Posted by

Hi,
>
I've a small problem. I have a table in which one column is date. I want
to count the records for statiscs in a temptable grouped by months lets
say 12 months back.
e.g.
month 1 counts 164 rec month 2 counts 87 records and so on.
I tried to solve this like this with a function SELECT COUNT(*) FROM TABLE
WHERE DATEDIFF(m,Col1,GETDATE())=@.counter.
But I don't know how to get this thing count from 0 up to 11 to get this
thing recursive.
Does anyone know how to tackel my problem? I wouls apreciate any answer.
Greetz to you all

|||Sjef ten Koppel (sjeftenkoppel@.home.nl) writes:

Quote:

Originally Posted by

Oops you are fast! thank you.
I could send you a create sql but I don't know how to extract sample data
from my db see att.


It does not have to be real-world data, you could just fill in some
sample data, and tell us what the result you want from the sample. That
helps to clarify your question.

But did not the query that Macro posted fit your needs?

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Great I tried your solution. It works great. Thank you!!
"MC" <marko.NOSPAMculo@.gmail.comschrieb im Newsbeitrag
news:er983u$64q$1@.ss408.t-com.hr...

Quote:

Originally Posted by

You need counts based on months? If your date column is datetime datatype,
something like this could work:
>
select count(*) as No, month(col1) as month, year (col1) as year
from table
where datediff(m, col1, getdate()) <= 12 -- if you want only last 12
months
group by month(col1) as month, year (col1) as year
>
If you posted create statements and some sample data I could test this...
>
>
MC
>
>
"Sjef ten Koppel" <sjeftenkoppel@.home.nlwrote in message
news:er97ad$qkb$1@.news6.zwoll1.ov.home.nl...

Quote:

Originally Posted by

>Hi,
>>
>I've a small problem. I have a table in which one column is date. I want
>to count the records for statiscs in a temptable grouped by months lets
>say 12 months back.
>e.g.
>month 1 counts 164 rec month 2 counts 87 records and so on.
>I tried to solve this like this with a function SELECT COUNT(*) FROM
>TABLE WHERE DATEDIFF(m,Col1,GETDATE())=@.counter.
>But I don't know how to get this thing count from 0 up to 11 to get this
>thing recursive.
>Does anyone know how to tackel my problem? I wouls apreciate any answer.
>Greetz to you all


>
>

|||Hallo,

Probeer dit eens:

select
YYYYMM=
(case
when datepart(m,Col1) < 10
then convert(int,convert(char(4),datepart(yyyy,Col1))+ '0'+convert(char(1),datepart(m,Col1)))
else convert(int,convert(char(4),datepart(yyyy,Col1))+c onvert(char(2),datepart(m,Col1)))
end), count(*) as [COUNT] from Table1

group by

(case
when datepart(m,Col1) < 10
then convert(int,convert(char(4),datepart(yyyy,Col1))+ '0'+convert(char(1),datepart(m,Col1)))
else convert(int,convert(char(4),datepart(yyyy,Col1))+c onvert(char(2),datepart(m,Col1)))
end)

order by

(case
when datepart(m,Col1) < 10
then convert(int,convert(char(4),datepart(yyyy,Col1))+ '0'+convert(char(1),datepart(m,Col1)))
else convert(int,convert(char(4),datepart(yyyy,Col1))+c onvert(char(2),datepart(m,Col1)))
end)

Groeten,

Wim Venema
delerium@.chello.nl
"Sjef ten Koppel" <sjeftenkoppel@.home.nlwrote in message news:er97ad$qkb$1@.news6.zwoll1.ov.home.nl...
Hi,

I've a small problem. I have a table in which one column is date. I want to
count the records for statiscs in a temptable grouped by months lets say 12
months back.
e.g.
month 1 counts 164 rec month 2 counts 87 records and so on.
I tried to solve this like this with a function SELECT COUNT(*) FROM TABLE
WHERE DATEDIFF(m,Col1,GETDATE())=@.counter.
But I don't know how to get this thing count from 0 up to 11 to get this
thing recursive.
Does anyone know how to tackel my problem? I wouls apreciate any answer.
Greetz to you allsql

Count on a date column

All,
I need to count dates in a column but how can i cut of the time hour minutes and seconds?
I need to rport how many records hav been added on one date...
con someone help me getting on the richt track?
regards
select count(*)
from tbl
where convert(varchar(8),dte,112) = '20040515'
select count(*)
from tbl
where dte >= '20040515' and dte < '20040515'
select dte = convert(varchar(8),dte,112), num = count(*)
from tbl
group by convert(varchar(8),dte,112)
order by convert(varchar(8),dte,112)
one of those should help.
Nigel Rivett
www.nigelrivett.net
*** Sent via Developersdex http://www.codecomments.com ***
Don't just participate in USENET...get rewarded for it!

Count of same column appearing twice in the query

SELECT CONVERT(char(10),min(dateadd(day, datediff(day,'19000101',d_datecreated)/7*7, '19000101')),101) as StartWeek,
CONVERT(char(10),max(dateadd(day, datediff(day,'19000101',dateadd(day,6,d_datecreated))/7*7, '19000101')),101) as EndWeek,
COUNT(*) AS MagazineAdCount
FROM orderformlineitems
where product_variant_id = '4010436709979469536'
group by datediff(day,'19000101',d_datecreated)/7
order by StartWeek ASC

Output
StartWeek EndWeek MagazineAdCount
04/16/2007 04/23/2007 8
04/23/2007 04/30/2007 15
04/30/2007 05/07/2007 5


SELECT CONVERT(char(10),min(dateadd(day, datediff(day,'19000101',d_datecreated)/7*7, '19000101')),101) as StartWeek,
CONVERT(char(10),max(dateadd(day, datediff(day,'19000101',dateadd(day,6,d_datecreated))/7*7, '19000101')),101) as EndWeek,
COUNT(*) AS BannerAdCount
FROM orderformlineitems
where product_variant_id = '7453910328410493551'
group by datediff(day,'19000101',d_datecreated)/7
order by StartWeek ASC

Output
StartWeek EndWeek BannerAdCount
04/16/2007 04/23/2007 15
04/23/2007 04/30/2007 21
04/30/2007 05/07/2007 22

I WANT THE BELOW OUTPUT THRU A SINGLE QUERY.....

StartWeek EndWeek MagazineAdCount BannerAdCount

04/16/2007 04/23/2007 8 15
04/23/2007 04/30/2007 15 21
04/30/2007 05/07/2007 5 22

Can anyone help please ?

Thanks

You can join these 2 query as single query..

Select Data1.Startweek,

Data1.EndWeek,

Data1.MagazineAdCount,

Data2.BannerAdCount

From

(SELECT CONVERT(char(10),min(dateadd(day, datediff(day,'19000101',d_datecreated)/7*7, '19000101')),101) as StartWeek,

CONVERT(char(10),max(dateadd(day, datediff(day,'19000101',dateadd(day,6,d_datecreated))/7*7, '19000101')),101) as EndWeek,

COUNT(*) AS MagazineAdCount

FROM orderformlineitems

where product_variant_id = '4010436709979469536'

group by datediff(day,'19000101',d_datecreated)/7 ) as Data1

Join

(SELECT CONVERT(char(10),min(dateadd(day, datediff(day,'19000101',d_datecreated)/7*7, '19000101')),101) as StartWeek,

CONVERT(char(10),max(dateadd(day, datediff(day,'19000101',dateadd(day,6,d_datecreated))/7*7, '19000101')),101) as EndWeek,

COUNT(*) AS BannerAdCount

FROM orderformlineitems

where product_variant_id = '7453910328410493551'

group by datediff(day,'19000101',d_datecreated)/7 ) as Data2 On Data1.StartWeek = Data2.StartWeek And Data1.EndWeek = Data2.EndWeek

|||Thank you !!|||

Use following query:

Code Snippet

SELECT CONVERT(char(10),min(dateadd(day, datediff(day,'19000101',d_datecreated)/7*7, '19000101')),101) as StartWeek,

CONVERT(char(10),max(dateadd(day, datediff(day,'19000101',dateadd(day,6,d_datecreated))/7*7, '19000101')),101) as EndWeek,

sum ( case product_variant_id when '4010436709979469536' then 1 else 0 end) AS MagazineAdCount,

sum ( case product_variant_id when '7453910328410493551' then 1 else 0 end) AS BannerAdCount

FROM orderformlineitems

where product_variant_id in ( '4010436709979469536', '7453910328410493551')

group by datediff(day,'19000101',d_datecreated)/7

order by StartWeek ASC

|||Thanks !!

count of records greater than?

Hello All,

Trying to set up a column in a grouped matrix that displays a count of all record over a specificed number.

The field I am counting are response time of transaction and I want to count how many were over 500 milliseconds. I though it would be something like this...

Code Snippet

=Count(Fields!ResponseTime.Value > "500")

However, this appears to just return the count of all rows and ignores the "500" part.

Am I missing something? If someone could post a alternate code snippet, that would be great.

Thanks in advance,

Clint

Hi Clint,

Try this expression

Code Snippet

=Count(iif (Fields!ResponseTime.Value > 500,1,nothing))

Best Regards,

Rajiv

|||

Thanks that works well..as an after thought, I need to add something in that would separate on of the field that has a different threshhold. Its grouped up and all but one has the 500 threshold count but one has 1000. Any ideas on how to separate it out?

I was thinking

Code Snippet

=Count(iif (Fields!ResponseTime.Value="QMEN" > 1000,1,nothing)) or Count(iif (Fields!ResponseTime.Value > 500,1,nothing))

But that errored out.|||

Need a second iff. Try just wrapping it around the timeout value

(I can't see your original post, so I'm just going to alter the innermost part of it. I don't think you meant the responsetime = QMEN..)

. . . > iif(XXXX.Value="QMEN", 1000, 500) . . .

|||

How would I incorporate that into?...

=Count(iif (Fields!ResponseTime.Value > 500,1,nothing))

Thanks.

|||

=Count(iif (Fields!ResponseTime.Value > iif(XXXX.Value="QMEN", 1000, 500) , 1, nothing))

Where XXXX is whatever field has the value QMEN

|||Awsome. Thanks so much. the worked perfectlysql

count of null values in columns

Hi,

I would like to ask how can I get count of null values in each column together?

I know I can use COUNT(*) - COUNT(<col>), but I need to explicitly name every column in the query.... is it possible without it?

SELECT COUNT(foo) WHERE Foo IS NULL;

GO

|||

Hi!

Thank you for your reply, however, this works only for one column. I meant how to do that if I don't know which columns are present, eg if I use SELECT * command...

|||

Here is my way:

select
coutOfNullsInCol01 = sum(case when col01 is null then 1 else 0 end),
coutOfNullsInCol02 = sum(case when col02 is null then 1 else 0 end)
from
Table

|||

This still requires you to know col01 and col02 names.

imagine table

A

B

x

NULL

NULL

NULL

x

NULL

What I'm looking for is something like

SELECT COUNTSofNULLSinCOLUMNS(*) FROM MyTable

which would return

1

3

You know I need to not specify any column names since I don't know them.

|||

If you're looking for an aggregate to count NULLS, you'll need to use a grouping function (such as GROUP BY) for that. Note that this function counts non-NULLS rather than NULLS, and still requires a name of the columns to work.

You could create a cursor of the column names by joining system tables to loop through them, but that sounds pretty un-elegant.

Why do you need this information? Are you looking for data density information?

|||

Hu! I dont know how to do this which lets you use a "SELECT" syntax.

But this can be done with a proc which takes the tables name as an input param and genrates an SQL statement dynamically to replace COL01, COL02... CONNN with acutal columns and give the same result.

Do you know how to do this? If not, wait for few minutes!

|||

Since I know row count I expect that non-NULLS or NULLS are the same for me.

System tables would be the solution, however, if the MyTable is not physically a table that won't help. Like SELECT thisstuff FROM (SELECT ...). And yes, since I'm not so experienced in SQL I just asked in case I'm missing some obvious elegant way. :)

This perhaps answers Laskhmana solution, which I guess is pretty similar idea.

Well... actually I was asking a year ago so I'll have to open some older project to answer your question, however I can't do it now. If I'll find out, I will let you know.

|||

here is the sample code (please note that this can be writen in a better way.):

declare

@.tableName sysname

set @.tableName = 'TableWithFewColumns'

-- you can create a proc with following code with above one as param

declare

@.strSQL varchar(8000)

if object_id('tempdb..#columns') is not null
drop table #columns

create table #columns(colName varchar(255))

insert into #columns
exec('select name from syscolumns (nolock) where id = object_id(''' + @.tableName + ''')')

set @.strSQL = ''

select
@.strSQL = @.strSQL + ',coutOfNulls' + colName + ' = sum(case when ' + colName + ' is null then 1 else 0 end)'
from
#columns

set @.strSQL = 'select ''' + @.tableName + ''' as SourceTableName' + @.strSQL + ' from ' + @.tableName

exec(@.strSQL)

count of null values in columns

Hi,

I would like to ask how can I get count of null values in each column together?

I know I can use COUNT(*) - COUNT(<col>), but I need to explicitly name every column in the query.... is it possible without it?

SELECT COUNT(foo) WHERE Foo IS NULL;

GO

|||

Hi!

Thank you for your reply, however, this works only for one column. I meant how to do that if I don't know which columns are present, eg if I use SELECT * command...

|||

Here is my way:

select
coutOfNullsInCol01 = sum(case when col01 is null then 1 else 0 end),
coutOfNullsInCol02 = sum(case when col02 is null then 1 else 0 end)
from
Table

|||

This still requires you to know col01 and col02 names.

imagine table

A B x NULL NULL NULL x NULL

What I'm looking for is something like

SELECT COUNTSofNULLSinCOLUMNS(*) FROM MyTable

which would return

1 3

You know I need to not specify any column names since I don't know them.

|||

If you're looking for an aggregate to count NULLS, you'll need to use a grouping function (such as GROUP BY) for that. Note that this function counts non-NULLS rather than NULLS, and still requires a name of the columns to work.

You could create a cursor of the column names by joining system tables to loop through them, but that sounds pretty un-elegant.

Why do you need this information? Are you looking for data density information?

|||

Hu! I dont know how to do this which lets you use a "SELECT" syntax.

But this can be done with a proc which takes the tables name as an input param and genrates an SQL statement dynamically to replace COL01, COL02... CONNN with acutal columns and give the same result.

Do you know how to do this? If not, wait for few minutes!

|||

Since I know row count I expect that non-NULLS or NULLS are the same for me.

System tables would be the solution, however, if the MyTable is not physically a table that won't help. Like SELECT thisstuff FROM (SELECT ...). And yes, since I'm not so experienced in SQL I just asked in case I'm missing some obvious elegant way. :)

This perhaps answers Laskhmana solution, which I guess is pretty similar idea.

Well... actually I was asking a year ago so I'll have to open some older project to answer your question, however I can't do it now. If I'll find out, I will let you know.

|||

here is the sample code (please note that this can be writen in a better way.):

declare

@.tableName sysname

set @.tableName = 'TableWithFewColumns'

-- you can create a proc with following code with above one as param

declare

@.strSQL varchar(8000)

if object_id('tempdb..#columns') is not null
drop table #columns

create table #columns(colName varchar(255))

insert into #columns
exec('select name from syscolumns (nolock) where id = object_id(''' + @.tableName + ''')')

set @.strSQL = ''

select
@.strSQL = @.strSQL + ',coutOfNulls' + colName + ' = sum(case when ' + colName + ' is null then 1 else 0 end)'
from
#columns

set @.strSQL = 'select ''' + @.tableName + ''' as SourceTableName' + @.strSQL + ' from ' + @.tableName

exec(@.strSQL)

Tuesday, March 27, 2012

Count of different values

Hi all,
I have a table in which there is a column that can only contain two values: Male and Female.
How should I write a query that will give me a total of both Male and Female?
For example: Male: 23 Female:27
Thanks!
SanderHello Sander,

this is a SQL statement that give you the needed datas in two records

select MaleFemale, count(1) from statistic
group by MaleFemale

Is that good for you ?

Greetings
Manfred Peter
(Alligator Company)
http://www.alligatorsql.com

Count Occurances in a column

Is there a way to count the number of times a character or string
appears in a column in a table row/column?
Example, tblTable has column StringData varchar(1000)
StringData contains the value "Mary Had A Little Lamb Lamb and Then It
Died"
I want to know how many times "Lamb" appears in this string.
Any help is appreciated.
ThanksOne popular way to do this is:
SELECT ( LEN( stringdata ) -
LEN( REPLACE( stringdata, 'Lamb', '' ) ) ) / LEN( 'Lamb' )
FROM tbl ;
Alternatively, you can use a table of sequentially incrementing numbers and
construct a generic logic using SUBSTRING functions too.
Anith|||laurenq uantrell wrote:
> Is there a way to count the number of times a character or string
> appears in a column in a table row/column?
> Example, tblTable has column StringData varchar(1000)
> StringData contains the value "Mary Had A Little Lamb Lamb and Then It
> Died"
> I want to know how many times "Lamb" appears in this string.
> Any help is appreciated.
> Thanks
DECLARE @.str VARCHAR(1000)
SET @.str= 'Lamb'
SELECT LEN(REPLACE(stringdata,@.str,@.str+'_'))-LEN(stringdata)
FROM tbltable;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||LEN has its problems, so here's one with DATALENGTH:
declare @.text nvarchar(4000)
declare @.string nvarchar(4000)
set @.text = N'Mary Had A Little Lamb Lamb and Then It Died'
set @.string = N'Lamb'
select (datalength(@.text) - datalength(replace(@.text, @.string, N''))) /
datalength(@.string)
ML
http://milambda.blogspot.com/|||Yup, that is right.
Anith|||DECLARE @.StringData varchar(1000)
DECLARE @.counter int
SET @.StringData = 'Mary Had A Little Lamb Lamb and Then It Died'
SET @.counter = 0
WHILE PATINDEX('%Lamb%',@.StringData) <> 0
BEGIN
SET @.counter = @.counter + 1
SET @.StringData = STUFF(@.StringData, PATINDEX('%Lamb%',@.StringData), 4, '')
END
PRINT @.counter
If you want to do this for all rows in a table, one way to accomplish this
is to put the above into a (gasp!) cursor:
DECLARE @.pkcol int --Change this to match that datatype of your PK column
DECLARE @.StringData varchar(1000)
DECLARE @.counter int
CREATE TABLE #results (pkcol int, StringCount int) --same here
DECLARE my_cursor CURSOR STATIC FORWARD_ONLY
FOR
SELECT pkcol, StringData FROM tblTable
FETCH NEXT FROM my_cursor INTO @.pkcol, @.StringData
WHILE (@.@.FETCH_STATUS = 0 )
BEGIN
SET @.counter = 0
WHILE PATINDEX('%Lamb%',@.StringData) <> 0
BEGIN
SET @.counter = @.counter + 1
SET @.StringData = STUFF(@.StringData, PATINDEX('%Lamb%',@.StringData), 4,
'')
END
INSERT INTO #results VALUES (@.pkcol, @.counter)
FETCH NEXT FROM my_cursor INTO @.pkcol, @.StringData
END
SELECT pkcol, StringCount FROM #results
"laurenq uantrell" wrote:

> Is there a way to count the number of times a character or string
> appears in a column in a table row/column?
> Example, tblTable has column StringData varchar(1000)
> StringData contains the value "Mary Had A Little Lamb Lamb and Then It
> Died"
> I want to know how many times "Lamb" appears in this string.
> Any help is appreciated.
> Thanks
>|||Mark,
A single SELECT with a table of numbers may do better than a cursor :
SELECT COUNT(*)
FROM Nbrs
WHERE SUBSTRING( @.stringdata, n, LEN( 'Lamb' ) ) = 'Lamb' ;
Anith|||There's only crap on TV, so...
http://milambda.blogspot.com/2006/0...th-strings.html
ML
http://milambda.blogspot.com/|||On 16 Feb 2006 14:11:22 -0800, laurenq uantrell wrote:

>Is there a way to count the number of times a character or string
>appears in a column in a table row/column?
>Example, tblTable has column StringData varchar(1000)
>StringData contains the value "Mary Had A Little Lamb Lamb and Then It
>Died"
>I want to know how many times "Lamb" appears in this string.
>Any help is appreciated.
>Thanks
Hi laurenq,
SELECT ( DATALENGTH(StringData)
- DATALENGTH(REPLACE(StringData, 'Lamb', '')) )
/ DATALENGTH('Lamb')
FROM tblTable
Hugo Kornelis, SQL Server MVP|||Thanks David and all other posters for these solutions.
lq

count number of lines in a clumn

The SP returns a column which contains
Error: 1212121
Error: 3434fsfa
Error: fdfdfd
Each above line has Char(10) + Char(13) attached so they will start a new line
Now I want to know the number of errors returns by using pattern "Error". Is
there any function I can use to do this?
thanks.In SQL you could do something like:
(LEN(columname) - LEN(REPLACE(columnname, 'Error' , '') ) / 5
I am not sure what the equivalent VB.Net syntax would look like to do it in
SRS.
"Helen" <Helen@.discussions.microsoft.com> wrote in message
news:B2FA56E5-AD24-4100-AD8B-B4CD7E771606@.microsoft.com...
> The SP returns a column which contains
> Error: 1212121
> Error: 3434fsfa
> Error: fdfdfd
> Each above line has Char(10) + Char(13) attached so they will start a new
> line
> Now I want to know the number of errors returns by using pattern "Error".
> Is
> there any function I can use to do this?
> thanks.

count measure question

Hi,

I have table with column which is containing two values ("Y" and "N") and I want to create measure which will count Y values and second measure which will count N value. How can I create it?

Thank you

Pavel

Is the Y/N column part of a fact or dimension table?

Probably the easiest solution would be to add two INT fields to your fact table named IsYes and IsNo. Set the values to 0 or 1 appropriately and use them as measures with a SUM aggregation function. It's simple but easy.

B.

Count is different on same table? Datetime column error?

Hi,
I have two servers, SV1 is a 24/7 OLTP server and SV2 is a backup
server. A Full Backup of the db (prototype) was taken from SV1 was
applied to SV2. One of the tables in the database has over 40 million
rows in it. My task is to keep any rows no older than 18 months.
SV1.Prototype.dbo.tblConsignment approx. 42,000,000 rows
SV2.Prototype.dbo.tblConsignment approx. 41,800,000 rows
this is correct as SV1 is constantly in use, so SV2 will always be a
day or two behind. The issue arrises when I perform my count on both
servers, when I run the following on SV1:
select count(*) from tblConsignments
where [Date] >= '2003-08-01 00:00:00.000'
the count is approx 25,500,000 rows, however when I run the exact same
statement on SV2 the count is 19,500,000. Why would there be a
discrepancy of 6,000,000? The collation is the same for both servers
(SV2 is a higher spec server, SV1 is 2K enterprise editions, SV2 2k
standard, both SP3a).
When I do a count year by year (on both servers) it comes to aprrox.
35,000,000 however the total for the tblConsignments is 42million.
Possibly the answer would be to check the data more throughly, however
I would like to know if Datetime columns can be set to different
versions?
Thanks
qh
Have you broken the data into smaller chunks? E.g. maybe a week or a month
is missing on one server...
This is my signature. It is a general reminder.
Please post DDL, sample data and desired results.
See http://www.aspfaq.com/5006 for info.
"Scott" <quackhandle1975@.yahoo.co.uk> wrote in message
news:1115224865.478078.231810@.o13g2000cwo.googlegr oups.com...
> Hi,
> I have two servers, SV1 is a 24/7 OLTP server and SV2 is a backup
> server. A Full Backup of the db (prototype) was taken from SV1 was
> applied to SV2. One of the tables in the database has over 40 million
> rows in it. My task is to keep any rows no older than 18 months.
> SV1.Prototype.dbo.tblConsignment approx. 42,000,000 rows
> SV2.Prototype.dbo.tblConsignment approx. 41,800,000 rows
> this is correct as SV1 is constantly in use, so SV2 will always be a
> day or two behind. The issue arrises when I perform my count on both
> servers, when I run the following on SV1:
> select count(*) from tblConsignments
> where [Date] >= '2003-08-01 00:00:00.000'
> the count is approx 25,500,000 rows, however when I run the exact same
> statement on SV2 the count is 19,500,000. Why would there be a
> discrepancy of 6,000,000? The collation is the same for both servers
> (SV2 is a higher spec server, SV1 is 2K enterprise editions, SV2 2k
> standard, both SP3a).
> When I do a count year by year (on both servers) it comes to aprrox.
> 35,000,000 however the total for the tblConsignments is 42million.
> Possibly the answer would be to check the data more throughly, however
> I would like to know if Datetime columns can be set to different
> versions?
> Thanks
> qh
>
|||Whenever you perform a COUNT(*), I'd recommend you use a MAXDOP (1) in
the SELECT to make sure the parallelism "issue" doesn't cause the
rowcount to be off.
David Gugick
Imceda Software
www.imceda.com
|||Hi,
Can you update the statistics and see.
UPDATE STATISTICS <TABLE NAME>
Otherwise execute the below command in both databases replacing count(*)
with *, but you need more space in ur hard disk on both servers
select * into old_records from tblConsignments where [Date] >= '2003-08-01
00:00:00.000'
Once the statement is completed try
select count(*) from old_records
But first try updating the statistics and see the difference.
Thanks
Hari
SQL Server MVP
"Scott" <quackhandle1975@.yahoo.co.uk> wrote in message
news:1115224865.478078.231810@.o13g2000cwo.googlegr oups.com...
> Hi,
> I have two servers, SV1 is a 24/7 OLTP server and SV2 is a backup
> server. A Full Backup of the db (prototype) was taken from SV1 was
> applied to SV2. One of the tables in the database has over 40 million
> rows in it. My task is to keep any rows no older than 18 months.
> SV1.Prototype.dbo.tblConsignment approx. 42,000,000 rows
> SV2.Prototype.dbo.tblConsignment approx. 41,800,000 rows
> this is correct as SV1 is constantly in use, so SV2 will always be a
> day or two behind. The issue arrises when I perform my count on both
> servers, when I run the following on SV1:
> select count(*) from tblConsignments
> where [Date] >= '2003-08-01 00:00:00.000'
> the count is approx 25,500,000 rows, however when I run the exact same
> statement on SV2 the count is 19,500,000. Why would there be a
> discrepancy of 6,000,000? The collation is the same for both servers
> (SV2 is a higher spec server, SV1 is 2K enterprise editions, SV2 2k
> standard, both SP3a).
> When I do a count year by year (on both servers) it comes to aprrox.
> 35,000,000 however the total for the tblConsignments is 42million.
> Possibly the answer would be to check the data more throughly, however
> I would like to know if Datetime columns can be set to different
> versions?
> Thanks
> qh
>
|||Hari,
Just for the record, the date string you give will be
interpreted as August 1, 2003 in some cases (such as us_english language
settings),
and as January 8, 2003 in others (such as french language setting). The two
SQL Server safe formats to use are (for August 1) '20030801' and
'2003-08-01T00:00:00.000'
Steve Kass
Drew University
Hari Prasad wrote:

>Hi,
>Can you update the statistics and see.
>UPDATE STATISTICS <TABLE NAME>
>Otherwise execute the below command in both databases replacing count(*)
>with *, but you need more space in ur hard disk on both servers
>select * into old_records from tblConsignments where [Date] >= '2003-08-01
>00:00:00.000'
>Once the statement is completed try
>select count(*) from old_records
>
>But first try updating the statistics and see the difference.
>Thanks
>Hari
>SQL Server MVP
>
>"Scott" <quackhandle1975@.yahoo.co.uk> wrote in message
>news:1115224865.478078.231810@.o13g2000cwo.googleg roups.com...
>
>
>
|||Hi ,
Update Statistics is used for statistics generation which is used for
determining the cost of the query , not sure how this will affect count(*) ,
please let me know if update statistics has any thing to do with count(*).
Regards
Vishal
"Hari Prasad" wrote:

> Hi,
> Can you update the statistics and see.
> UPDATE STATISTICS <TABLE NAME>
> Otherwise execute the below command in both databases replacing count(*)
> with *, but you need more space in ur hard disk on both servers
> select * into old_records from tblConsignments where [Date] >= '2003-08-01
> 00:00:00.000'
> Once the statement is completed try
> select count(*) from old_records
>
> But first try updating the statistics and see the difference.
> Thanks
> Hari
> SQL Server MVP
>
> "Scott" <quackhandle1975@.yahoo.co.uk> wrote in message
> news:1115224865.478078.231810@.o13g2000cwo.googlegr oups.com...
>
>
|||Hi ,
Update Statistics is used for statistics generation which is used for
determining the cost of the query and selecting the appropriate index , not
sure how this will affect count(*) , please let me know if update statistics
has any thing to do with count(*).
Regards
Vishal

Count is different on same table? Datetime column error?

Hi,
I have two servers, SV1 is a 24/7 OLTP server and SV2 is a backup
server. A Full Backup of the db (prototype) was taken from SV1 was
applied to SV2. One of the tables in the database has over 40 million
rows in it. My task is to keep any rows no older than 18 months.
SV1.Prototype.dbo.tblConsignment approx. 42,000,000 rows
SV2.Prototype.dbo.tblConsignment approx. 41,800,000 rows
this is correct as SV1 is constantly in use, so SV2 will always be a
day or two behind. The issue arrises when I perform my count on both
servers, when I run the following on SV1:
select count(*) from tblConsignments
where [Date] >= '2003-08-01 00:00:00.000'
the count is approx 25,500,000 rows, however when I run the exact same
statement on SV2 the count is 19,500,000. Why would there be a
discrepancy of 6,000,000? The collation is the same for both servers
(SV2 is a higher spec server, SV1 is 2K enterprise editions, SV2 2k
standard, both SP3a).
When I do a count year by year (on both servers) it comes to aprrox.
35,000,000 however the total for the tblConsignments is 42million.
Possibly the answer would be to check the data more throughly, however
I would like to know if Datetime columns can be set to different
versions?
Thanks
qhHave you broken the data into smaller chunks? E.g. maybe a week or a month
is missing on one server...
--
This is my signature. It is a general reminder.
Please post DDL, sample data and desired results.
See http://www.aspfaq.com/5006 for info.
"Scott" <quackhandle1975@.yahoo.co.uk> wrote in message
news:1115224865.478078.231810@.o13g2000cwo.googlegroups.com...
> Hi,
> I have two servers, SV1 is a 24/7 OLTP server and SV2 is a backup
> server. A Full Backup of the db (prototype) was taken from SV1 was
> applied to SV2. One of the tables in the database has over 40 million
> rows in it. My task is to keep any rows no older than 18 months.
> SV1.Prototype.dbo.tblConsignment approx. 42,000,000 rows
> SV2.Prototype.dbo.tblConsignment approx. 41,800,000 rows
> this is correct as SV1 is constantly in use, so SV2 will always be a
> day or two behind. The issue arrises when I perform my count on both
> servers, when I run the following on SV1:
> select count(*) from tblConsignments
> where [Date] >= '2003-08-01 00:00:00.000'
> the count is approx 25,500,000 rows, however when I run the exact same
> statement on SV2 the count is 19,500,000. Why would there be a
> discrepancy of 6,000,000? The collation is the same for both servers
> (SV2 is a higher spec server, SV1 is 2K enterprise editions, SV2 2k
> standard, both SP3a).
> When I do a count year by year (on both servers) it comes to aprrox.
> 35,000,000 however the total for the tblConsignments is 42million.
> Possibly the answer would be to check the data more throughly, however
> I would like to know if Datetime columns can be set to different
> versions?
> Thanks
> qh
>|||Whenever you perform a COUNT(*), I'd recommend you use a MAXDOP (1) in
the SELECT to make sure the parallelism "issue" doesn't cause the
rowcount to be off.
--
David Gugick
Imceda Software
www.imceda.com|||Hi,
Can you update the statistics and see.
UPDATE STATISTICS <TABLE NAME>
Otherwise execute the below command in both databases replacing count(*)
with *, but you need more space in ur hard disk on both servers
select * into old_records from tblConsignments where [Date] >= '2003-08-01
00:00:00.000'
Once the statement is completed try
select count(*) from old_records
But first try updating the statistics and see the difference.
Thanks
Hari
SQL Server MVP
"Scott" <quackhandle1975@.yahoo.co.uk> wrote in message
news:1115224865.478078.231810@.o13g2000cwo.googlegroups.com...
> Hi,
> I have two servers, SV1 is a 24/7 OLTP server and SV2 is a backup
> server. A Full Backup of the db (prototype) was taken from SV1 was
> applied to SV2. One of the tables in the database has over 40 million
> rows in it. My task is to keep any rows no older than 18 months.
> SV1.Prototype.dbo.tblConsignment approx. 42,000,000 rows
> SV2.Prototype.dbo.tblConsignment approx. 41,800,000 rows
> this is correct as SV1 is constantly in use, so SV2 will always be a
> day or two behind. The issue arrises when I perform my count on both
> servers, when I run the following on SV1:
> select count(*) from tblConsignments
> where [Date] >= '2003-08-01 00:00:00.000'
> the count is approx 25,500,000 rows, however when I run the exact same
> statement on SV2 the count is 19,500,000. Why would there be a
> discrepancy of 6,000,000? The collation is the same for both servers
> (SV2 is a higher spec server, SV1 is 2K enterprise editions, SV2 2k
> standard, both SP3a).
> When I do a count year by year (on both servers) it comes to aprrox.
> 35,000,000 however the total for the tblConsignments is 42million.
> Possibly the answer would be to check the data more throughly, however
> I would like to know if Datetime columns can be set to different
> versions?
> Thanks
> qh
>|||Hari,
Just for the record, the date string you give will be
interpreted as August 1, 2003 in some cases (such as us_english language
settings),
and as January 8, 2003 in others (such as french language setting). The two
SQL Server safe formats to use are (for August 1) '20030801' and
'2003-08-01T00:00:00.000'
Steve Kass
Drew University
Hari Prasad wrote:
>Hi,
>Can you update the statistics and see.
>UPDATE STATISTICS <TABLE NAME>
>Otherwise execute the below command in both databases replacing count(*)
>with *, but you need more space in ur hard disk on both servers
>select * into old_records from tblConsignments where [Date] >= '2003-08-01
>00:00:00.000'
>Once the statement is completed try
>select count(*) from old_records
>
>But first try updating the statistics and see the difference.
>Thanks
>Hari
>SQL Server MVP
>
>"Scott" <quackhandle1975@.yahoo.co.uk> wrote in message
>news:1115224865.478078.231810@.o13g2000cwo.googlegroups.com...
>
>>Hi,
>>I have two servers, SV1 is a 24/7 OLTP server and SV2 is a backup
>>server. A Full Backup of the db (prototype) was taken from SV1 was
>>applied to SV2. One of the tables in the database has over 40 million
>>rows in it. My task is to keep any rows no older than 18 months.
>>SV1.Prototype.dbo.tblConsignment approx. 42,000,000 rows
>>SV2.Prototype.dbo.tblConsignment approx. 41,800,000 rows
>>this is correct as SV1 is constantly in use, so SV2 will always be a
>>day or two behind. The issue arrises when I perform my count on both
>>servers, when I run the following on SV1:
>>select count(*) from tblConsignments
>>where [Date] >= '2003-08-01 00:00:00.000'
>>the count is approx 25,500,000 rows, however when I run the exact same
>>statement on SV2 the count is 19,500,000. Why would there be a
>>discrepancy of 6,000,000? The collation is the same for both servers
>>(SV2 is a higher spec server, SV1 is 2K enterprise editions, SV2 2k
>>standard, both SP3a).
>>When I do a count year by year (on both servers) it comes to aprrox.
>>35,000,000 however the total for the tblConsignments is 42million.
>>Possibly the answer would be to check the data more throughly, however
>>I would like to know if Datetime columns can be set to different
>>versions?
>>Thanks
>>qh
>>
>
>|||Hi ,
Update Statistics is used for statistics generation which is used for
determining the cost of the query , not sure how this will affect count(*) ,
please let me know if update statistics has any thing to do with count(*).
Regards
Vishal
"Hari Prasad" wrote:
> Hi,
> Can you update the statistics and see.
> UPDATE STATISTICS <TABLE NAME>
> Otherwise execute the below command in both databases replacing count(*)
> with *, but you need more space in ur hard disk on both servers
> select * into old_records from tblConsignments where [Date] >= '2003-08-01
> 00:00:00.000'
> Once the statement is completed try
> select count(*) from old_records
>
> But first try updating the statistics and see the difference.
> Thanks
> Hari
> SQL Server MVP
>
> "Scott" <quackhandle1975@.yahoo.co.uk> wrote in message
> news:1115224865.478078.231810@.o13g2000cwo.googlegroups.com...
> > Hi,
> >
> > I have two servers, SV1 is a 24/7 OLTP server and SV2 is a backup
> > server. A Full Backup of the db (prototype) was taken from SV1 was
> > applied to SV2. One of the tables in the database has over 40 million
> > rows in it. My task is to keep any rows no older than 18 months.
> >
> > SV1.Prototype.dbo.tblConsignment approx. 42,000,000 rows
> > SV2.Prototype.dbo.tblConsignment approx. 41,800,000 rows
> >
> > this is correct as SV1 is constantly in use, so SV2 will always be a
> > day or two behind. The issue arrises when I perform my count on both
> > servers, when I run the following on SV1:
> >
> > select count(*) from tblConsignments
> > where [Date] >= '2003-08-01 00:00:00.000'
> >
> > the count is approx 25,500,000 rows, however when I run the exact same
> > statement on SV2 the count is 19,500,000. Why would there be a
> > discrepancy of 6,000,000? The collation is the same for both servers
> > (SV2 is a higher spec server, SV1 is 2K enterprise editions, SV2 2k
> > standard, both SP3a).
> >
> > When I do a count year by year (on both servers) it comes to aprrox.
> > 35,000,000 however the total for the tblConsignments is 42million.
> > Possibly the answer would be to check the data more throughly, however
> > I would like to know if Datetime columns can be set to different
> > versions?
> >
> > Thanks
> >
> > qh
> >
>
>|||Hi ,
Update Statistics is used for statistics generation which is used for
determining the cost of the query and selecting the appropriate index , not
sure how this will affect count(*) , please let me know if update statistics
has any thing to do with count(*).
Regards
Vishal|||Hi Guys,
many thanks for the replies, I have taken your suggestions and tried
both UPDATE STATISTICS and the OPTION (MAXDOP 1) however I am still
returning the same rowcount anomoly. The main thing that has me
stumped is that the db on SV2 is a backup from the db on SV1!! I have
even created a small table based on a rowcount between certain years.
SV1 SV2
older 6,486,356 6,486,356
2002 9,893,118 9,893,118
2003 10,402,588 10,402,588
2004 11,268,420 11,268,419
2005+ 4,014,450 3,862,644
Totals 35,578,576 35,426,769
However as I originally mentioned there is over 41,000,000 rows in both
the corresponding tables? My next plan is to perform a simple data
complare on each table.
Thanks again
qhsql

Count is different on same table? Datetime column error?

Hi,
I have two servers, SV1 is a 24/7 OLTP server and SV2 is a backup
server. A Full Backup of the db (prototype) was taken from SV1 was
applied to SV2. One of the tables in the database has over 40 million
rows in it. My task is to keep any rows no older than 18 months.
SV1.Prototype.dbo.tblConsignment approx. 42,000,000 rows
SV2.Prototype.dbo.tblConsignment approx. 41,800,000 rows
this is correct as SV1 is constantly in use, so SV2 will always be a
day or two behind. The issue arrises when I perform my count on both
servers, when I run the following on SV1:
select count(*) from tblConsignments
where [Date] >= '2003-08-01 00:00:00.000'
the count is approx 25,500,000 rows, however when I run the exact same
statement on SV2 the count is 19,500,000. Why would there be a
discrepancy of 6,000,000? The collation is the same for both servers
(SV2 is a higher spec server, SV1 is 2K enterprise editions, SV2 2k
standard, both SP3a).
When I do a count year by year (on both servers) it comes to aprrox.
35,000,000 however the total for the tblConsignments is 42million.
Possibly the answer would be to check the data more throughly, however
I would like to know if Datetime columns can be set to different
versions?
Thanks
qhHave you broken the data into smaller chunks? E.g. maybe a week or a month
is missing on one server...
This is my signature. It is a general reminder.
Please post DDL, sample data and desired results.
See http://www.aspfaq.com/5006 for info.
"Scott" <quackhandle1975@.yahoo.co.uk> wrote in message
news:1115224865.478078.231810@.o13g2000cwo.googlegroups.com...
> Hi,
> I have two servers, SV1 is a 24/7 OLTP server and SV2 is a backup
> server. A Full Backup of the db (prototype) was taken from SV1 was
> applied to SV2. One of the tables in the database has over 40 million
> rows in it. My task is to keep any rows no older than 18 months.
> SV1.Prototype.dbo.tblConsignment approx. 42,000,000 rows
> SV2.Prototype.dbo.tblConsignment approx. 41,800,000 rows
> this is correct as SV1 is constantly in use, so SV2 will always be a
> day or two behind. The issue arrises when I perform my count on both
> servers, when I run the following on SV1:
> select count(*) from tblConsignments
> where [Date] >= '2003-08-01 00:00:00.000'
> the count is approx 25,500,000 rows, however when I run the exact same
> statement on SV2 the count is 19,500,000. Why would there be a
> discrepancy of 6,000,000? The collation is the same for both servers
> (SV2 is a higher spec server, SV1 is 2K enterprise editions, SV2 2k
> standard, both SP3a).
> When I do a count year by year (on both servers) it comes to aprrox.
> 35,000,000 however the total for the tblConsignments is 42million.
> Possibly the answer would be to check the data more throughly, however
> I would like to know if Datetime columns can be set to different
> versions?
> Thanks
> qh
>|||Whenever you perform a COUNT(*), I'd recommend you use a MAXDOP (1) in
the SELECT to make sure the parallelism "issue" doesn't cause the
rowcount to be off.
David Gugick
Imceda Software
www.imceda.com|||Hi,
Can you update the statistics and see.
UPDATE STATISTICS <TABLE NAME>
Otherwise execute the below command in both databases replacing count(*)
with *, but you need more space in ur hard disk on both servers
select * into old_records from tblConsignments where [Date] >= '2003-08-
01
00:00:00.000'
Once the statement is completed try
select count(*) from old_records
But first try updating the statistics and see the difference.
Thanks
Hari
SQL Server MVP
"Scott" <quackhandle1975@.yahoo.co.uk> wrote in message
news:1115224865.478078.231810@.o13g2000cwo.googlegroups.com...
> Hi,
> I have two servers, SV1 is a 24/7 OLTP server and SV2 is a backup
> server. A Full Backup of the db (prototype) was taken from SV1 was
> applied to SV2. One of the tables in the database has over 40 million
> rows in it. My task is to keep any rows no older than 18 months.
> SV1.Prototype.dbo.tblConsignment approx. 42,000,000 rows
> SV2.Prototype.dbo.tblConsignment approx. 41,800,000 rows
> this is correct as SV1 is constantly in use, so SV2 will always be a
> day or two behind. The issue arrises when I perform my count on both
> servers, when I run the following on SV1:
> select count(*) from tblConsignments
> where [Date] >= '2003-08-01 00:00:00.000'
> the count is approx 25,500,000 rows, however when I run the exact same
> statement on SV2 the count is 19,500,000. Why would there be a
> discrepancy of 6,000,000? The collation is the same for both servers
> (SV2 is a higher spec server, SV1 is 2K enterprise editions, SV2 2k
> standard, both SP3a).
> When I do a count year by year (on both servers) it comes to aprrox.
> 35,000,000 however the total for the tblConsignments is 42million.
> Possibly the answer would be to check the data more throughly, however
> I would like to know if Datetime columns can be set to different
> versions?
> Thanks
> qh
>|||Hari,
Just for the record, the date string you give will be
interpreted as August 1, 2003 in some cases (such as us_english language
settings),
and as January 8, 2003 in others (such as french language setting). The two
SQL Server safe formats to use are (for August 1) '20030801' and
'2003-08-01T00:00:00.000'
Steve Kass
Drew University
Hari Prasad wrote:

>Hi,
>Can you update the statistics and see.
>UPDATE STATISTICS <TABLE NAME>
>Otherwise execute the below command in both databases replacing count(*)
>with *, but you need more space in ur hard disk on both servers
>select * into old_records from tblConsignments where [Date] >= '2003-08
-01
>00:00:00.000'
>Once the statement is completed try
>select count(*) from old_records
>
>But first try updating the statistics and see the difference.
>Thanks
>Hari
>SQL Server MVP
>
>"Scott" <quackhandle1975@.yahoo.co.uk> wrote in message
>news:1115224865.478078.231810@.o13g2000cwo.googlegroups.com...
>
>
>|||Hi ,
Update Statistics is used for statistics generation which is used for
determining the cost of the query , not sure how this will affect count(*)
,
please let me know if update statistics has any thing to do with count(*).
Regards
Vishal
"Hari Prasad" wrote:

> Hi,
> Can you update the statistics and see.
> UPDATE STATISTICS <TABLE NAME>
> Otherwise execute the below command in both databases replacing count(*)
> with *, but you need more space in ur hard disk on both servers
> select * into old_records from tblConsignments where [Date] >= '2003-0
8-01
> 00:00:00.000'
> Once the statement is completed try
> select count(*) from old_records
>
> But first try updating the statistics and see the difference.
> Thanks
> Hari
> SQL Server MVP
>
> "Scott" <quackhandle1975@.yahoo.co.uk> wrote in message
> news:1115224865.478078.231810@.o13g2000cwo.googlegroups.com...
>
>|||Hi ,
Update Statistics is used for statistics generation which is used for
determining the cost of the query and selecting the appropriate index , not
sure how this will affect count(*) , please let me know if update statistic
s
has any thing to do with count(*).
Regards
Vishal

Count if condition

hi guys

I need to do a count on a column in my table but i have to check for a condition first.

Here is my sample data

ProviderdateRegionDHBDHBNamePHOPHONamePracticePracticenamePracticeAddressPractice_StartdatePractice_EnddatePractitionerPractitionerNamePractitioner_StartdatePractitioner_EnddateLocum1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000045Horatepai15 Epiha Street, Paraparaumu1/07/200329201Geraldine Victoria MacKenzie Jordan8/06/200531/10/2005no1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000045Horatepai15 Epiha Street, Paraparaumu1/07/200322079Glenn Morton Colquhoun1/03/2006NO1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000045Horatepai15 Epiha Street, Paraparaumu1/07/200314121Meaburn Charles Staniland1/07/2003NO1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000045Horatepai15 Epiha Street, Paraparaumu1/07/20039877Philip White1/07/2003NO1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000045Horatepai15 Epiha Street, Paraparaumu1/07/200311678Susan Prudence Wilson1/07/2003NO1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000045Horatepai15 Epiha Street, Paraparaumu1/07/20033881Wilfred Travis Wilson5/01/2002yes1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000052Paraparaumu Medical Centre92-94 Kapiti Road, Paraparaumu1/07/200322742Adrian Howard Beaumont Gilliland13/01/200528/10/2005NO1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000052Paraparaumu Medical Centre92-94 Kapiti Road, Paraparaumu1/07/200318188Amanda Mary Clarke1/07/2003NO1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000052Paraparaumu Medical Centre92-94 Kapiti Road, Paraparaumu1/07/200332909Andre Honda Garib29/12/2005no1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000052Paraparaumu Medical Centre92-94 Kapiti Road, Paraparaumu1/07/200313042Christopher Alan Fawcett1/07/2003NO1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000052Paraparaumu Medical Centre92-94 Kapiti Road, Paraparaumu1/07/200316556Jennifer Maree O'Donnell1/07/200322/12/2005YES1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000052Paraparaumu Medical Centre92-94 Kapiti Road, Paraparaumu1/07/200313650Timothy Stapleton Smith1/07/2003NO1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000046Paul Norton Surgery51 Kapiti Road, Paraparaumu1/07/200314621Paul Stephen Norton1/07/2003NO1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000053Raumati Road Surgery23 Raumati Road, Raumati Beach, Paraparaumu1/07/200311202Katherine Dana Stone3/10/20057/10/2005yes1/01/2006Central091Capital & Coast DHB585171Kapiti PHO-585171585171_0000053Raumati Road Surgery23 Raumati Road, Raumati Beach, Paraparaumu1/07/200313048Robyn Lynette Crow1/07/2003NO

now i have to add two new columns as LocumYes and LocumNo
In Locumyes column I have to count the number of 'yes' in the locum column grouped by practitioner and in locumno i have to count the number of 'no' for that practitioner.

The situation is a practitioner can work on more than one practice and he can work as a 'yes' locum in one,'no' locum' in another or vice versa.It can be of any sort of combination.

so I have to do a query which should group by practitioner and count the number of yes and no for each practitioner..

Thanks

Mita

Hi. You can do this with subqueries included in the SELECT statement.

Let's suppose your table is named tblPractices:

SELECT Practicioner,

(SELECT COUNT(Locum) FROM tblPractices LocumYes WHERE Locum = 'yes' AND LocumYes.Practicioner = tblPractices.Practicioner) AS NumYes,

(SELECT COUNT(Locum) FROM tblPractices LocumNo WHERE Locum = 'no' AND LocumNo.Practicioner = tblPractices.Practicioner) AS NumNo

FROM tblPractices

GROUP BY Practicioner


Tony Alicea
http://www.theabstractionpoint.com
clarity of mind and creativity in application software development...

Sunday, March 25, 2012

COUNT FUNCTION ON MULTIPLE COLUMNS

I have a database that contains a column for UnitName , BeginDate and
EndDate.

I want to pass two parameters (@.BeginDate and @.EndDate) and retrieve a
table of values

that include UnitName along with Counts for each UnitName.

SELECT UnitName, COUNT(BeginDate) AS Start
(SELECT COUNT(EndDate) AS Finish WHERE EndDate BETWEEN @.BeginDate AND
@.EndDate)
FROM Table
WHERE BeginDate BETWEEN @.BeginDate AND @.EndDate
GROUP BY UnitName
ORDER BY UnitName

This works. But when I try to add another count by using a subselect I
get an error dealing with GROUP BY not including the column in my
subselect.

How is the best way to Count two columns using Group By.k4 wrote:

Quote:

Originally Posted by

I have a database that contains a column for UnitName , BeginDate and
EndDate.
>
I want to pass two parameters (@.BeginDate and @.EndDate) and retrieve a
table of values
>
that include UnitName along with Counts for each UnitName.
>
SELECT UnitName, COUNT(BeginDate) AS Start
(SELECT COUNT(EndDate) AS Finish WHERE EndDate BETWEEN @.BeginDate AND
@.EndDate)
FROM Table
WHERE BeginDate BETWEEN @.BeginDate AND @.EndDate
GROUP BY UnitName
ORDER BY UnitName
>
This works. But when I try to add another count by using a subselect I
get an error dealing with GROUP BY not including the column in my
subselect.
>
How is the best way to Count two columns using Group By.


Assuming the BeginDates are always <= the corresponding EndDates, you
can do:

SELECT UnitName,
COUNT(CASE WHEN BeginDate
BETWEEN @.BeginDate AND @.EndDate THEN 1 END) AS BeginDate,
COUNT(CASE WHEN EndDate
BETWEEN @.BeginDate AND @.EndDate THEN 1 END) AS EndDate
FROM tbl
WHERE BeginDate <= @.EndDate
AND EndDate >= @.BeginDate
GROUP BY UnitName
ORDER BY UnitName;

--
David Portas, SQL Server MVP

Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.

SQL Server Books Online:
http://msdn2.microsoft.com/library/...US,SQL.90).aspx
--

count distinct

can you set up a measure with "countdistinct" where some column in fact tabl
e
<> 0
i want a count of members in my fact table where total_bal <> 0 by all
dimensions
does someone have an exampleYou can create a separate cube with a "Distinct Count" measure for the
member column, and set the "Source Table Filter" for the cube to
"total_bal <> 0". This cube can be combined with existing cubes in a
virtual cube.
- Deepak
Deepak Puri
Microsoft MVP - SQL Server
*** Sent via Developersdex http://www.codecomments.com ***
Don't just participate in USENET...get rewarded for it!|||I have cube with staff dimension which has staff_member_id as a level
Cube has metrics for example total_bal
I want to count distinct staff_member id's for each level in my time dimensi
on
daily, weekly, monthly etc where total_bal > 0
Is this possible to do within an MDX, can you send me an example of
something like this
Creating separate cubes would mean we have to create atleast 25 cubes as we
have 25 different measures we want to calculate like above
Thanks
"Deepak Puri" wrote:

> You can create a separate cube with a "Distinct Count" measure for the
> member column, and set the "Source Table Filter" for the cube to
> "total_bal <> 0". This cube can be combined with existing cubes in a
> virtual cube.
>
> - Deepak
> Deepak Puri
> Microsoft MVP - SQL Server
> *** Sent via Developersdex http://www.codecomments.com ***
> Don't just participate in USENET...get rewarded for it!
>|||Assuming that there is a [tot_bal] "sum" measure, based on a "tot_bal"
fact table field, and that this field is always >= 0, MDX can be used to
count [staff_member_id] members for a given node in the time hierarchy:
[vbcol=seagreen]
With Member [Measures].[StaffCount] as
'Count(Filter(NonEmptyCrossJoin(
[Staff].[staff_member_id].Members,
{[Time].CurrentMember}, 1),
[Measures].[tot_bal] > 0))'[vbcol=seagreen]
- Deepak
Deepak Puri
Microsoft MVP - SQL Server
*** Sent via Developersdex http://www.codecomments.com ***
Don't just participate in USENET...get rewarded for it!|||this is my exact MDX statement
i have result set out oof this MDX like this in columns which separate WTD,
MTD etc
MEMBERCAPTION thisdate wktd monthtd lastmonth ytd
1008 21 43 90 100 8
97
StaffCount 12 23 12 13 88
8
Can you help me write Measures.Staffcount please..
select 1 as col1, * from openquery (ROP_OLAP, "
with
member [time].[thisdate] as 'aggregate(time.[20040430]:time.&#
91;20040430])'
member [time].[wktd] as 'aggregate(time.[20040426]:time.[2
0040430])'
member [time].[monthtd] as
'aggregate(openingperiod([day],ancestor([20040430],[month])):tim
e.[20040430])'
member [time].[lastmonth] as 'aggregate(time.[20040301]:time.
1;20040331])'
member [time].[ytd] as 'aggregate(time.[20040301]:time.[20
040430])'
-- Member [Measures].[StaffCount] as ''
member [measures].[1008] as '[measures].[ECH_Acw_Time]'
select { [measures].[StaffCount] , [measures].[1008] }
on rows,
{[timeset]} on columns
from unifinal_web
where ([Function].[All Function].[01003])
")
"Deepak Puri" wrote:

> Assuming that there is a [tot_bal] "sum" measure, based on a "tot_bal"
> fact table field, and that this field is always >= 0, MDX can be used to
> count [staff_member_id] members for a given node in the time hierarchy
:
>
> With Member [Measures].[StaffCount] as
> 'Count(Filter(NonEmptyCrossJoin(
> [Staff].[staff_member_id].Members,
> {[Time].CurrentMember}, 1),
> [Measures].[tot_bal] > 0))'
>
> - Deepak
> Deepak Puri
> Microsoft MVP - SQL Server
> *** Sent via Developersdex http://www.codecomments.com ***
> Don't just participate in USENET...get rewarded for it!
>|||To count staff where [Measures].[1008] > 0:
[vbcol=seagreen]
With Member [Measures].[StaffCount] as
'Count(Filter(
[Staff].[staff_member_id].Members,
[Measures].[1008] > 0))'[vbcol=seagreen]
- Deepak
Deepak Puri
Microsoft MVP - SQL Server
*** Sent via Developersdex http://www.codecomments.com ***
Don't just participate in USENET...get rewarded for it!|||I tied this and it makes the MX extremely slow, 50 secs instead of 2 secs
which it was taking earlier
is there any way to speed this up or some other mechanism
"Deepak Puri" wrote:

> To count staff where [Measures].[1008] > 0:
>
> With Member [Measures].[StaffCount] as
> 'Count(Filter(
> [Staff].[staff_member_id].Members,
> [Measures].[1008] > 0))'
>
> - Deepak
> Deepak Puri
> Microsoft MVP - SQL Server
> *** Sent via Developersdex http://www.codecomments.com ***
> Don't just participate in USENET...get rewarded for it!
>|||You could try AS 2005 (Yukon), which supports aggregation of distinct
count measures.
If the different time ranges are defined in Named Sets (like [YTDSet]),
then staff count for each set could be optimized by NonEmptyCrossJoin()
pre-filtering.
Short of these options, you could try optimizing the longer time ranges,
using the approach discussed in this thread, where Chris Webb discusses
the possibility to optimize a time series, and I posted some sample MDX
code. You can refer to Chris's BI Blog (referenced in this thread) for
more details:
http://groups-beta.google.com/_grou...serv_er.olap/m.
.
Newsgroups: microsoft.public.sqlserver.ola_p
Subject: RE: Problem with MDX query
Chris Webb Dec 31 2004, 4:01 am
- Hide quoted text -
- Show quoted text -
I don't think the query is hanging, I think it's just taking a very long
time
to complete! Summing up all those days in your date range is going to
take a
long time, plus I'll bet that your second query (because it doesn't
mention
the YearMonthDay dimension at all) probably hits aggregations whereas
your
first query doesn't.
Since this is a fairly common problem I've just made it the subject of
the
first entry of my new blog, which you can read here:
http://spaces.msn.com/members/__cwebbbi/Blog/cns!1pi7ETChsJ1un___2s41jm9
I.|||Deepak
I could not go to the link and am not an expret an MDX to understand your
code so easily
can you pls re-write this according to your recomendation so it can improve
in speed
THANKS!!!!
select 1 as col1, * from openquery (ROP_OLAP, "
with
member [time].[thisdate] as 'aggregate(time.[20040430]:time.&#
91;20040430])'
member [time].[wktd] as 'aggregate(time.[20040426]:time.[2
0040430])'
member [time].[monthtd] as
'aggregate(openingperiod([day],ancestor([20040430],[month])):tim
e.[20040430])'
member [time].[lastmonth] as 'aggregate(time.[20040301]:time.
1;20040331])'
member [time].[ytd] as 'aggregate(time.[20040301]:time.[20
040430])'
Member [Measures].[StaffCount] as
'Count(Filter([Staff].[agent].Members,[Measures].[CAS_IC_C]
> 0))'
member [measures].[1008] as '[measures].[ECH_Acw_Time]'
set [timeset] as '{[time].[thisdate], [time].[wktd]
, [time].[monthtd],
[time].[lastmonth], [time].[ytd]}'
select { [measures].[1008], [Measures].[StaffCount] }
on rows,
{[timeset]} on columns
from unifinal_web
where ([Function].[All Function].[01003])")|||You should really work this out yourself, since I don't have your cube
to test against, but something like:
[vbcol=seagreen]
select 1 as col1, * from openquery (ROP_OLAP, "
with
set [ThisDateSet] as
'{time.[20040430]:time.[20040430]}'
set [WktdSet] as
'{time.[20040426]:time.[20040430]}'
set [MonthdSet] as
'{openingperiod([day],ancestor([20040430],[month])):time.&#
91;20040430]}'
set [LastMonthSet] as
'{time.[20040301]:time.[20040331]}'
set [YTDSet] as
'{time.[20040301]:time.[20040430]}'
Member [Measures].[InMonthd] as
'Except(Descendants([Time].CurrentMember,,LEAVES),[MonthdSet]).Count
=
0'
Member [Measures].[InLastMonth] as
'Except(Descendants([Time].CurrentMember,,LEAVES),[LastMonthSet]).Co
unt
= 0'
Member [Measures].[InYTD] as
'Except(Descendants([Time].CurrentMember,,LEAVES),[YTDSet]).Count =
0'
Set [MonthdOpt] as 'Filter([Time].Members, [Measures].[InMon
thd]
AND Not ( [Measures].[InMonthd], [Time].Parent))'
Set [LastMonthOpt] as 'Filter([Time].Members, [Measures].[In
LastMonth]
AND Not ( [Measures].[InLastMonth], [Time].Parent))'
Set [YTDOpt] as 'Filter([Time].Members, [Measures].[InYTD]
AND Not ( [Measures].[InYTD], [Time].Parent))'
member [time].[thisdate] as 'aggregate([WktdSet])'
member [time].[wktd] as 'aggregate([WktdSet])'
member [time].[monthtd] as 'aggregate([MonthdOpt])'
member [time].[lastmonth] as 'aggregate([LastMonthOpt])'
member [time].[ytd] as 'aggregate([YTDOpt])'
member [measures].[1008] as '[measures].[ECH_Acw_Time]'
Member [Measures].[StaffCount] as
'Count(Filter(NonEmptyCrossJoin(
[Staff].[staff_member_id].Members),
[Measures].[CAS_IC_C] > 0))'
set [timeset] as '{[time].[thisdate], [time].[wktd]
, [time].[monthtd],
[time].[lastmonth], [time].[ytd]}'
select { [measures].[1008], [Measures].[StaffCount]
} on rows,
{[timeset]} on columns
from unifinal_web
where ([Function].[All Function].[01003])")[vbcol=seagreen]
- Deepak
Deepak Puri
Microsoft MVP - SQL Server
*** Sent via Developersdex http://www.codecomments.com ***
Don't just participate in USENET...get rewarded for it!