Showing posts with label columns. Show all posts
Showing posts with label columns. Show all posts

Thursday, March 29, 2012

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 Conditonal Formatting

Hi,

I have a report where conditional formatting is applied based on being compared to a fixed value in a second dataset. There are several columns where this is applied, and I would like to be able to count all where the condition is true (ie >= corresponding column in dataset2, background green) and all that are false (ie < dataset2, background red) and use that data in the same report and create a percentage.

Not sure whether the reporting layer is the place to do this, or whether to create a separate table and populate that with 1's and 0's beforehand and then use that data additionally in the report?

Many thanks

The usual way to do this is to use SUM() instead of COUNT(), like this:

Code Snippet

SUM(IIF(<condition is true>,1,0))

HTH,

>L<

|||

Hi,

For backgroud coloring, add to this to the column BackgroundColor property:

Code Snippet

=iif(<condition> = 0, "Green", "Red")

|||

Have a look at Brian Welcker's Blog for his post on Custom Aggregates:

http://blogs.msdn.com/bwelcker/archive/2005/05/10/416306.aspx

In the Code block (available from the Report Properties dialog), you would add:

Dim orderIDs As System.Collections.Hashtable
Dim total As Double

Function MyFunc(ByVal orderID As Object, ByVal freight As Obect) As Double
If (orderIDs Is Nothing) Then
orderIDs = New System.Collections.Hashtable
End If
If (orderID Is Nothing) Then
MyFunc = total
Else
If (Not orderIDs.Contains(orderID)) Then
total = total + freight
orderIDs.Add(orderID, freight)
End If
MyFunc = total
End If
End Function

In your report, you add a hidden textbox with the value expression to compute the value:

=Sum(Code.MyFunc(Fields!OrderID.Value, Fields!Freight.Value))

In the footer of the table, you add a textbox with the value expression:

=Code.MyFunc(Nothing, Fields!Freight.Value)

to return the total value.

I believe it provides the functionality you need.

Larry

|||

Thanks, I think this will work within a column, therefore I get a total at the bottom of each column.

I also need a total at the end of each row (crosstab style), but obviously each column has a separate textbox and separate conditional formatting expression. It still boils down to whether that condition is true or false - do you know if this is possile or is it better suited to the database level?

eg for all condition true is >= value in dataset 2

dataset2 - baseline comparison table

col1, col2, col3

40,2,0

dataset1 - data

col1, col2, col3

20,2,4

45,0,0

what i'd like is to be able to include on the report that 2 true conditions were met and also include the actual data

col1, col2, col3, SumTrue

20,2,4,2

45,0,0,2

Appreciate everyone's help so far - i've got the formatting (ie red, green) working - just wondering if the sum of conditions across columns will work

|||

Actually I think it will still work, and without any exciting code. but possibly I'm not clear from your examples what your SumTrue column means, because it says "2" on each of the rows and I only see 1 match in each row against your baseline table?

>L<

|||

Hi..

The condition for true in this case is where the result is >= to the comparison table, in the example there are 2 on each row that are >= to the comparison table.

I have just got back to looking at this again and tried the following in the group footer of one of the columns

=Sum(IIF(Fields!col1.Value >= First(Fields!col1.Value, "BaseTable"),1,0))

and get an error saying aggregate functions cannot be nested in other aggregate functions.

|||

>>the result is >= to the comparison table

OIC. I thought it had to be = to be true. I apologize, I didn't see the > in your original post, although I see now that you said so! I will have to repro this to test, which is why I am noticing the > now . Hang on, doing that...

Well, it does work, as I said, to do the thing you asked about ( "adding across").

IOW, assuming DataSet2 is your real values and DataSet1 is the baseline, this works fine to get your fourth column across, as I expected:


Code Snippet

=IIF(Fields!col1.Value >= First(Fields!col1.Value, "DataSet1"),1,0) +

IIF(Fields!col2.Value >= First(Fields!col2.Value, "DataSet1"),1,0) +

IIF(Fields!col3.Value >= First(Fields!col3.Value, "DataSet1"),1,0)

For your group footer, though, you would have to do the custom aggregate bit.

That really seems like the long way around, though. Are you absolutely sure you shouldn't be doing this at the data level?

To illustrate: I did this to represent your the baseline data in my repro:

Code Snippet

SELECT 40 AS col1, 2 AS col2, 0 AS col3

and then this to represent the real data:

Code Snippet

SELECT 20 AS col1,2 AS col2,4 AS col3
UNION
SELECT 45 AS col1,0 AS col2, 0 AS col3

Ignoring the UNION, for a moment, because it was just there to give me two dummy rows in the real data, wouldn't we be better off if we did the following at the SQL level? What we're after is a Cartesian join with the one-row baseline data, which you can get with any dummy-true condition; I used 1=1 here:

Code Snippet

SELECT col1, col2, col3, basecol1, basecol2,basecol3,
CASE WHEN col1 >= basecol1 THEN 1 ELSE 0 END AS col1Comp,
CASE WHEN col2 >= basecol2 THEN 1 ELSE 0 END AS col2Comp,
CASE WHEN col3 >= basecol3 THEN 1 ELSE 0 END AS col3Comp
FROM (SELECT 20 AS col1,2 AS col2,4 AS col3
UNION
SELECT 45 AS col1,0 AS col2, 0 AS col3) real
JOIN (SELECT 40 AS basecol1, 2 AS basecol2, 0 AS basecol3) baseline
ON 1= 1

(Again just treat the UNIONed set as a placeholder for your real data and the literals on the right side of the join as a placeholder for however you get your single row of baseline data. )

Now you have everything you need in one dataset.

I added the col1Comp, col2Comp, and col3Comp columns just to make life easier on the reporting end, you really could do without them and do the >= comparisons against col1 versus basecol1 etc, because you would no longer be nesting aggregates. I included the three calculated columns because I don't see any reason to do any of this work on the reporting level, frankly...

For colors you could then write simple expressions like

=IIF(Fields!col1Comp.Value=1,"Green","Red")

Going across, you would only need to write this:

=Fields!col1Comp.Value + Fields!col2Comp.Value + Fields!col3Comp.Value

Going down is a simple =Sum(Fields1!col1Comp.Value) and of course the bottom right is a simple sum of the addition you see above.

>L<

|||

Absolutely spot on !! Works a treat.

Appreciate your help on this.

Thanks,

Mike

|||

Yea verily, data is a beautiful thing <g>.

Enjoy,

>L<

Count of Columns <> 0

How would you count the number of columns with a value not equal to 0 for
each row in a table?

Thanks!

Joe"Joe User" <joe@.user.com> wrote in message
news:c4s5vp$6je$1@.tribune.mayo.edu...
> How would you count the number of columns with a value not equal to 0 for
> each row in a table?
> Thanks!
> Joe

Here's one way:

select PrimaryKeyColumn,
case when col1 = 0 then 0 else 1 end +
case when col2 = 0 then 0 else 1 end +
case when col3 = 0 then 0 else 1 end +
...
case when coln = 0 then 0 else 1 end as 'NonZeroColumns'
from
dbo.MyTable

Simon|||Excellent!

Thanks!

Next question....
How does someone relatively new to tsql learn this sort of thing?

TIA

"Simon Hayes" <sql@.hayes.ch> wrote in message
news:4071a1c0$1_3@.news.bluewin.ch...
> "Joe User" <joe@.user.com> wrote in message
> news:c4s5vp$6je$1@.tribune.mayo.edu...
> > How would you count the number of columns with a value not equal to 0
for
> > each row in a table?
> > Thanks!
> > Joe
> Here's one way:
> select PrimaryKeyColumn,
> case when col1 = 0 then 0 else 1 end +
> case when col2 = 0 then 0 else 1 end +
> case when col3 = 0 then 0 else 1 end +
> ...
> case when coln = 0 then 0 else 1 end as 'NonZeroColumns'
> from
> dbo.MyTable
>
> Simon|||"Joe User" <joe@.user.com> wrote in message
news:c4sa4g$c6p$1@.tribune.mayo.edu...
> Excellent!
> Thanks!
> Next question....
> How does someone relatively new to tsql learn this sort of thing?
> TIA

<snip
Get a good book or two - there are some suggestions here:

http://vyaskn.tripod.com/sqlbooks.htm

But don't forget Books Online itself - it's very helpful to read through the
TSQL reference part. I don't mean read every word (unless you have a lot of
time on your hands...), but it helps to have an idea of what's available in
the language. Even if you only vaguely remember what a keyword does, or if
you only remember the name, you can always look it up. The list of functions
is another useful page to review, for the same reason. The
SELECT/INSERT/UPDATE/DELETE entries are very important, as are the CREATE
XXXX entries - all of them are linked to lots of related information, so you
can go into as much detail as you want.

Simon|||>> How would you count the number of columns with a value not equal to
0 for each row in a table? <<

SELECT keycol,
ABS(SIGN(col1)) +
ABS(SIGN(col2)) +
ABS(SIGN(col3)) + .. AS non_zero_tally
FROM Foobar;

count multiple distinct columns

I want to build query to return how many rows are in this query:
select distinct c1, c2 from t1

But SQL won't accept this syntax:
select count (distinct c1, c2) from t1

Does someone know how to count multiple distinct columns? Thanks.

--
Disclaimer: This post is solely an individual opinion and does not speak on
behalf of any organization.One method is to use a derived table:

SELECT COUNT(*)
FROM (
SELECT DISTINCT c1, c2
FROM t1) AS t1

--
Hope this helps.

Dan Guzman
SQL Server MVP

"Dean" <noreply@.fakeaddress.com> wrote in message
news:cd1o36$aho$1@.news01.intel.com...
> I want to build query to return how many rows are in this query:
> select distinct c1, c2 from t1
> But SQL won't accept this syntax:
> select count (distinct c1, c2) from t1
> Does someone know how to count multiple distinct columns? Thanks.
>
> --
> Disclaimer: This post is solely an individual opinion and does not speak
on
> behalf of any organization.|||"Dan Guzman" <danguzman@.nospam-earthlink.net> wrote in message
news:8D_Ic.1568
> One method is to use a derived table:
> SELECT COUNT(*)
> FROM (
> SELECT DISTINCT c1, c2
> FROM t1) AS t1

Thanks! I was trying
SELECT COUNT(*) FROM (SELECT DISTINCT c1, c2 FROM t1)
but it wouldn't work without the "AS t1" at the end.

--
Disclaimer: This post is solely an individual opinion and does not speak on
behalf of any organization.|||Try this out..

SELECT COUNT(*) FROM (select distinct c1, c2 from t1)T

Sunday, March 25, 2012

count having question.

Hello,
I have a table which has 3 columns,
[dispatcher], [dueDate],[Delivered]
I am trying to write a query which tells me which dispatchers delivered
their package on time
So I have,
select dispatcher, count(datedif(d,dueDate, Delivered)) as [onTime],
count(datedif(d,dueDate, Delivered)) as [Late]
from table
group by dispatcher
having some magical code goes here
And I need to create a table like
[dispatcher] [ontTime] [Late]
Mario - 10 - 20
Luis - 32 - 10
Is there a way to do this without havving to use multiple queries and
temporary tables?
ThanksTry the following, untested:
select dispatcher,
(select count(*)
from table t2
where t2.dispatcher = t.dispatcher
and datediff(d,dueDate, Delivered) = 0) as [onTime],
(select count(*)
from table t2
where t2.dispatcher = t.dispatcher
and datediff(d,dueDate, Delivered) > 0) as [Late]
from table t
group by dispatcher
Q
"Marcelo" wrote:

> Hello,
> I have a table which has 3 columns,
> [dispatcher], [dueDate],[Delivered]
> I am trying to write a query which tells me which dispatchers delivered
> their package on time
> So I have,
> select dispatcher, count(datedif(d,dueDate, Delivered)) as [onTime],
> count(datedif(d,dueDate, Delivered)) as [Late]
> from table
> group by dispatcher
> having some magical code goes here
> And I need to create a table like
> [dispatcher] [ontTime] [Late]
> Mario - 10 - 20
> Luis - 32 - 10
> Is there a way to do this without havving to use multiple queries and
> temporary tables?
>
> Thanks
>
>|||An alternate method might be:
/*Assumes that early delivery (delivered before duedate) is considered
to be OnTime
*/
SELECT dispatcher,
onTime = SUM(CASE WHEN DATEDIFF(d, dueDate, Delivered) <= 0
THEN 1 ELSE 0 END),
Late = SUM(CASE WHEN DATEDIFF(d, dueDate, Delivered) > 0
THEN 1 ELSE 0 END)
FROM table t
GROUP BY dispatcher
Untested.
Stu|||which would be faster?
I have the same pattern as yours that is "select sum(case...)" but it's
becoming quite slow as the number of row grows.
Will the solution from Q run faster and if so, some explanations would
certainly help me understand better for next time.
Thx.
Stu wrote:
> An alternate method might be:
> /*Assumes that early delivery (delivered before duedate) is considered
> to be OnTime
> */
> SELECT dispatcher,
> onTime = SUM(CASE WHEN DATEDIFF(d, dueDate, Delivered) <= 0
> THEN 1 ELSE 0 END),
> Late = SUM(CASE WHEN DATEDIFF(d, dueDate, Delivered) > 0
> THEN 1 ELSE 0 END)
> FROM table t
> GROUP BY dispatcher
> Untested.
> Stu
>|||Christian, are you the original poster? If so, you changed your logon,
so I am uncertain. I typically use the syntax that I provided because
its cleaner, and it performs well for me. Since I don't have access to
the data (and the indexes), I can't really test it to see; however, if
you're the original poster, you can (and then you can let me know which
performs better).
Do you know how to use Execution plans in Query Analyzer? That'll go a
long way to helping you determin which syntax is best.
Stu

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 fields of a table

How can I find out how many columns in a table ?
Thanksselect * from information_schema.columns where table_name = 'mytable'
or
select count(*) from information_schema.columns where table_name = 'mytable'
hth.
Mark
www.dovetaildatabases.com
"Catelin wang" <cwang@.cemstone.com> wrote in message
news:uEcty0a%23EHA.1604@.TK2MSFTNGP12.phx.gbl...
> How can I find out how many columns in a table ?
> Thanks
>|||Thanks.
"Mark" <field027@.idonotlikejunkmail.umn.edu> wrote in message
news:uEZqZ5a%23EHA.2452@.TK2MSFTNGP14.phx.gbl...
> select * from information_schema.columns where table_name = 'mytable'
> or
> select count(*) from information_schema.columns where table_name =
'mytable'
> hth.
> Mark
> www.dovetaildatabases.com
> "Catelin wang" <cwang@.cemstone.com> wrote in message
> news:uEcty0a%23EHA.1604@.TK2MSFTNGP12.phx.gbl...
>

count fields of a table

How can I find out how many columns in a table ?
Thanks
select * from information_schema.columns where table_name = 'mytable'
or
select count(*) from information_schema.columns where table_name = 'mytable'
hth.
Mark
www.dovetaildatabases.com
"Catelin wang" <cwang@.cemstone.com> wrote in message
news:uEcty0a%23EHA.1604@.TK2MSFTNGP12.phx.gbl...
> How can I find out how many columns in a table ?
> Thanks
>
|||Thanks.
"Mark" <field027@.idonotlikejunkmail.umn.edu> wrote in message
news:uEZqZ5a%23EHA.2452@.TK2MSFTNGP14.phx.gbl...
> select * from information_schema.columns where table_name = 'mytable'
> or
> select count(*) from information_schema.columns where table_name =
'mytable'
> hth.
> Mark
> www.dovetaildatabases.com
> "Catelin wang" <cwang@.cemstone.com> wrote in message
> news:uEcty0a%23EHA.1604@.TK2MSFTNGP12.phx.gbl...
>

count fields of a table

How can I find out how many columns in a table ?
Thanksselect * from information_schema.columns where table_name = 'mytable'
or
select count(*) from information_schema.columns where table_name = 'mytable'
hth.
Mark
www.dovetaildatabases.com
"Catelin wang" <cwang@.cemstone.com> wrote in message
news:uEcty0a%23EHA.1604@.TK2MSFTNGP12.phx.gbl...
> How can I find out how many columns in a table ?
> Thanks
>|||Thanks.
"Mark" <field027@.idonotlikejunkmail.umn.edu> wrote in message
news:uEZqZ5a%23EHA.2452@.TK2MSFTNGP14.phx.gbl...
> select * from information_schema.columns where table_name = 'mytable'
> or
> select count(*) from information_schema.columns where table_name ='mytable'
> hth.
> Mark
> www.dovetaildatabases.com
> "Catelin wang" <cwang@.cemstone.com> wrote in message
> news:uEcty0a%23EHA.1604@.TK2MSFTNGP12.phx.gbl...
> > How can I find out how many columns in a table ?
> >
> > Thanks
> >
> >
>

Count Distinct

Hello,

I was wondering does count(distinct) work on multiiple columns? I get syntax error on "," with the following code.

select count(distinct cookie1, cookie2) from BookersLookers_DataSet

Thanks,

-Lawrence

You cant pass more than one column in COUNT function..

Use the following query...

Code Snippet

Select Count(*) From

(Select cookie1,cookie2 From BookersLookers_DataSet Group By cookie1,cookie2) as Data

--Or

Select Count(*) From

(Select Distinct cookie1,cookie2 From BookersLookers_DataSet) as Data

|||

Actually, to get the count(), you need to use a GROUP BY, and if you use a GROUP BY, then DISTINCT is not necessary (redundent).

Code Snippet


SELECT
Cookie1,
Cookie2,
[Count] = count(1)
FROM BookersLookers_Dataset
GROUP BY
Cookie1,
Cookie2

Thursday, March 22, 2012

Count

I am trying to count entries into each column heading by zip code, but when I
run the script below I get the same count across all columns. Can someone
tell/show me how to make these unquie counts?
Thanks in advance.
SELECT DISTINCT P.ZIP,
COUNT (evC.day_care_center) AS 'Day Care',
COUNT (evC.drop_care) AS 'Drop-In Care',
COUNT (evC.family_day_care) AS 'Family day care',
COUNT (evC.financial) AS 'Financial',
COUNT (evC.montessori_program2)AS 'Montessori program',
COUNT (evC.nanny_service) AS 'Nanny service',
COUNT (evC.nursery_schl_lrn_ct) AS 'Nursery school - learn centers',
COUNT (evC.parenting_info) AS 'Parenting information',
COUNT (evC.sick_child_care) AS 'Sick child care',
COUNT (evC.special_needs)AS 'Special needs',
COUNT (evC.summer_camp_care)AS 'Summer camps/care',
COUNT (evC.temporary) AS 'Temporary',
COUNT (evC.transportation2)AS 'Transportation',
COUNT (evC.support_groups) AS 'Support groups',
COUNT (evC.other) AS 'Other'
FROM Patient_Elg pe
INNER JOIN Patient p ON pe.Patient_Key = p.Patient_Key
INNER JOIN evChildcareintakea evC ON pe.Patient_Key = evC.Patient_Key
WHERE (pe.Payor_Key = 59)
AND p.create_date BETWEEN '1/1/07' AND '12/31/07'
GROUP BY P.Zip
--
Message posted via SQLMonster.com
http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server/200801/1Put the DISTINCT keyword inside the COUNT():
SELECT P.ZIP,
COUNT (DISTINCT evC.day_care_center) AS 'Day Care',
COUNT (DISTINCT evC.drop_care) AS 'Drop-In Care',
...
Tom
----
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA, MCITP, MCTS
SQL Server MVP
Toronto, ON Canada
https://mvp.support.microsoft.com/profile/Tom.Moreau
"Jay via SQLMonster.com" <u7124@.uwe> wrote in message
news:7efd1fc265539@.uwe...
I am trying to count entries into each column heading by zip code, but when
I
run the script below I get the same count across all columns. Can someone
tell/show me how to make these unquie counts?
Thanks in advance.
SELECT DISTINCT P.ZIP,
COUNT (evC.day_care_center) AS 'Day Care',
COUNT (evC.drop_care) AS 'Drop-In Care',
COUNT (evC.family_day_care) AS 'Family day care',
COUNT (evC.financial) AS 'Financial',
COUNT (evC.montessori_program2)AS 'Montessori program',
COUNT (evC.nanny_service) AS 'Nanny service',
COUNT (evC.nursery_schl_lrn_ct) AS 'Nursery school - learn centers',
COUNT (evC.parenting_info) AS 'Parenting information',
COUNT (evC.sick_child_care) AS 'Sick child care',
COUNT (evC.special_needs)AS 'Special needs',
COUNT (evC.summer_camp_care)AS 'Summer camps/care',
COUNT (evC.temporary) AS 'Temporary',
COUNT (evC.transportation2)AS 'Transportation',
COUNT (evC.support_groups) AS 'Support groups',
COUNT (evC.other) AS 'Other'
FROM Patient_Elg pe
INNER JOIN Patient p ON pe.Patient_Key = p.Patient_Key
INNER JOIN evChildcareintakea evC ON pe.Patient_Key = evC.Patient_Key
WHERE (pe.Payor_Key = 59)
AND p.create_date BETWEEN '1/1/07' AND '12/31/07'
GROUP BY P.Zip
--
Message posted via SQLMonster.com
http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server/200801/1|||I'm guessing you might need to COUNT the distinct values for each
column. If that is the case:
SELECT P.ZIP,
COUNT (DISTINCT evC.day_care_center) AS 'Day Care',
COUNT (DISTINCT evC.drop_care) AS 'Drop-In Care',
etc.
If that is not what you need please elaborate on what you actually
hope to see.
Note that since you were already doing a GROUP BY there was no purpose
to having a DISTINCT for the entire query.
Roy Harvey
Beacon Falls, CT
On Wed, 30 Jan 2008 15:49:59 GMT, "Jay via SQLMonster.com" <u7124@.uwe>
wrote:
>I am trying to count entries into each column heading by zip code, but when I
>run the script below I get the same count across all columns. Can someone
>tell/show me how to make these unquie counts?
>Thanks in advance.
>SELECT DISTINCT P.ZIP,
> COUNT (evC.day_care_center) AS 'Day Care',
> COUNT (evC.drop_care) AS 'Drop-In Care',
> COUNT (evC.family_day_care) AS 'Family day care',
> COUNT (evC.financial) AS 'Financial',
> COUNT (evC.montessori_program2)AS 'Montessori program',
> COUNT (evC.nanny_service) AS 'Nanny service',
> COUNT (evC.nursery_schl_lrn_ct) AS 'Nursery school - learn centers',
> COUNT (evC.parenting_info) AS 'Parenting information',
> COUNT (evC.sick_child_care) AS 'Sick child care',
> COUNT (evC.special_needs)AS 'Special needs',
> COUNT (evC.summer_camp_care)AS 'Summer camps/care',
> COUNT (evC.temporary) AS 'Temporary',
> COUNT (evC.transportation2)AS 'Transportation',
> COUNT (evC.support_groups) AS 'Support groups',
> COUNT (evC.other) AS 'Other'
>FROM Patient_Elg pe
> INNER JOIN Patient p ON pe.Patient_Key = p.Patient_Key
> INNER JOIN evChildcareintakea evC ON pe.Patient_Key = evC.Patient_Key
>WHERE (pe.Payor_Key = 59)
> AND p.create_date BETWEEN '1/1/07' AND '12/31/07'
>GROUP BY P.Zip|||I made the changes you suggested and it did make the counts unique but they
are not correct by column heading/category. To check I displayed all the
information for zip code 55901 under the column 'Day Care' for '07. I came up
with a count of 200, but for this script I only get 11. How can I get all
records to count?
Thanks again for your help in advance
Roy Harvey (SQL Server MVP) wrote:
>I'm guessing you might need to COUNT the distinct values for each
>column. If that is the case:
>SELECT P.ZIP,
> COUNT (DISTINCT evC.day_care_center) AS 'Day Care',
> COUNT (DISTINCT evC.drop_care) AS 'Drop-In Care',
>etc.
>If that is not what you need please elaborate on what you actually
>hope to see.
>Note that since you were already doing a GROUP BY there was no purpose
>to having a DISTINCT for the entire query.
>Roy Harvey
>Beacon Falls, CT
>>I am trying to count entries into each column heading by zip code, but when I
>>run the script below I get the same count across all columns. Can someone
>[quoted text clipped - 25 lines]
>> AND p.create_date BETWEEN '1/1/07' AND '12/31/07'
>>GROUP BY P.Zip
--
Message posted via http://www.sqlmonster.com|||Usually the fastest way to get answers to questions like this is to give us
the SQL statements to create sample tables and load those tables with sample
data (see www.aspfaq.com/5006 for how to do this). Then tell us the result
you would want to see from that sample data. That keeps us from having to
guess what you want, and you will get an answer that has been tested against
your sample data.
Tom
"jpettigrew via SQLMonster.com" <u7124@.uwe> wrote in message
news:7efdb43406fee@.uwe...
>I made the changes you suggested and it did make the counts unique but they
> are not correct by column heading/category. To check I displayed all the
> information for zip code 55901 under the column 'Day Care' for '07. I came
> up
> with a count of 200, but for this script I only get 11. How can I get all
> records to count?
> Thanks again for your help in advance
> Roy Harvey (SQL Server MVP) wrote:
>>I'm guessing you might need to COUNT the distinct values for each
>>column. If that is the case:
>>SELECT P.ZIP,
>> COUNT (DISTINCT evC.day_care_center) AS 'Day Care',
>> COUNT (DISTINCT evC.drop_care) AS 'Drop-In Care',
>>etc.
>>If that is not what you need please elaborate on what you actually
>>hope to see.
>>Note that since you were already doing a GROUP BY there was no purpose
>>to having a DISTINCT for the entire query.
>>Roy Harvey
>>Beacon Falls, CT
>>I am trying to count entries into each column heading by zip code, but
>>when I
>>run the script below I get the same count across all columns. Can someone
>>[quoted text clipped - 25 lines]
>> AND p.create_date BETWEEN '1/1/07' AND '12/31/07'
>>GROUP BY P.Zip
> --
> Message posted via http://www.sqlmonster.com
>|||What Tom Cooper said. SHOW us what you have, and what you want.
Your original query counted all the rows for the zip code. All the
columns were the same because COUNT(columnname) returns a count of all
the rows with non-null values for that column, and apparently every
row was non-null. If there are 200 rows for a zip code, why would you
expect any number except 200 for day_care_center or drop_care?
Roy Harvey
Beacon Falls, CT
On Wed, 30 Jan 2008 16:56:33 GMT, "jpettigrew via SQLMonster.com"
<u7124@.uwe> wrote:
>I made the changes you suggested and it did make the counts unique but they
>are not correct by column heading/category. To check I displayed all the
>information for zip code 55901 under the column 'Day Care' for '07. I came up
>with a count of 200, but for this script I only get 11. How can I get all
>records to count?
>Thanks again for your help in advance
>Roy Harvey (SQL Server MVP) wrote:
>>I'm guessing you might need to COUNT the distinct values for each
>>column. If that is the case:
>>SELECT P.ZIP,
>> COUNT (DISTINCT evC.day_care_center) AS 'Day Care',
>> COUNT (DISTINCT evC.drop_care) AS 'Drop-In Care',
>>etc.
>>If that is not what you need please elaborate on what you actually
>>hope to see.
>>Note that since you were already doing a GROUP BY there was no purpose
>>to having a DISTINCT for the entire query.
>>Roy Harvey
>>Beacon Falls, CT
>>I am trying to count entries into each column heading by zip code, but when I
>>run the script below I get the same count across all columns. Can someone
>>[quoted text clipped - 25 lines]
>> AND p.create_date BETWEEN '1/1/07' AND '12/31/07'
>>GROUP BY P.Zip|||Because of HIPAA compliance it is difficult to provide information contained
in one of the tables. How do you suggest I provide the information? If i was
not specific in my previous posts I apologize I am trying to total the
columns in the script by zip code, but do not seem to be getting all the
information.
Tom Cooper wrote:
>Usually the fastest way to get answers to questions like this is to give us
>the SQL statements to create sample tables and load those tables with sample
>data (see www.aspfaq.com/5006 for how to do this). Then tell us the result
>you would want to see from that sample data. That keeps us from having to
>guess what you want, and you will get an answer that has been tested against
>your sample data.
>Tom
>>I made the changes you suggested and it did make the counts unique but they
>> are not correct by column heading/category. To check I displayed all the
>[quoted text clipped - 28 lines]
>> AND p.create_date BETWEEN '1/1/07' AND '12/31/07'
>>GROUP BY P.Zip
--
Message posted via SQLMonster.com
http://www.sqlmonster.com/Uwe/Forums.aspx/sql-server/200801/1|||On Wed, 30 Jan 2008 20:11:22 GMT, Jay via SQLMonster.com wrote:
>Because of HIPAA compliance it is difficult to provide information contained
>in one of the tables. How do you suggest I provide the information?
Hi Jay,
* Post the table structure as CREATE TABLE statements, including all
constraints, properties, and indexes.
* Post the data as INSERT statements. It doesn't need to be the real
data, a made-up sample that illustrates the problem is just as well
(probably even better, as there is no need to posts thousands or even
millions of rows when you can illustrate the problem with ten). I don't
think HIPAA disallows the posting of made-up data.
* Post the expected results.
--
Hugo Kornelis, SQL Server MVP
My SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis|||On Jan 30, 9:49=A0pm, "Jay via SQLMonster.com" <u7124@.uwe> wrote:
> I am trying to count entries into each column heading by zip code, but whe=n I
> run the script below I get the same count across all columns. Can someone
> tell/show me how to make these unquie counts?
> Thanks in advance.
> SELECT =A0DISTINCT P.ZIP,
> =A0 =A0 =A0 =A0 COUNT (evC.day_care_center) AS 'Day Care',
> =A0 =A0 =A0 =A0 COUNT (evC.drop_care) AS 'Drop-In Care',
> =A0 =A0 =A0 =A0 COUNT (evC.family_day_care) AS 'Family day care',
> =A0 =A0 =A0 =A0 COUNT (evC.financial) AS 'Financial',
> =A0 =A0 =A0 =A0 COUNT (evC.montessori_program2)AS 'Montessori program',
> =A0 =A0 =A0 =A0 COUNT (evC.nanny_service) AS 'Nanny service',
> =A0 =A0 =A0 =A0 COUNT (evC.nursery_schl_lrn_ct) AS 'Nursery school - learn= centers',
> =A0 =A0 =A0 =A0 COUNT (evC.parenting_info) AS 'Parenting information',
> =A0 =A0 =A0 =A0 COUNT (evC.sick_child_care) AS 'Sick child care',
> =A0 =A0 =A0 =A0 COUNT (evC.special_needs)AS 'Special needs',
> =A0 =A0 =A0 =A0 COUNT (evC.summer_camp_care)AS 'Summer camps/care',
> =A0 =A0 =A0 =A0 COUNT (evC.temporary) AS 'Temporary',
> =A0 =A0 =A0 =A0 COUNT (evC.transportation2)AS 'Transportation',
> =A0 =A0 =A0 =A0 COUNT (evC.support_groups) AS 'Support groups',
> =A0 =A0 =A0 =A0 COUNT (evC.other) AS 'Other'
> FROM =A0 =A0Patient_Elg pe
> =A0 =A0 =A0 =A0 INNER JOIN Patient p ON pe.Patient_Key =3D p.Patient_Key
> =A0 =A0 =A0 =A0 INNER JOIN evChildcareintakea evC ON pe.Patient_Key =3D ev=C.Patient_Key
> WHERE =A0 =A0 (pe.Payor_Key =3D 59)
> =A0 =A0 =A0 =A0 AND p.create_date BETWEEN '1/1/07' AND '12/31/07'
> GROUP BY P.Zip
> --
> Message posted via SQLMonster.comhttp://www.sqlmonster.com/Uwe/Forums.aspx=
/sql-server/200801/1
Hi Jay,
I think you need to do each count(distinct field) separately and store
them (maybe into a variable). For example:
Declare @.zip int, @.center int, etc
Select @.zip =3D select count(distinct p.zip)
FROM Patient_Elg pe
INNER JOIN Patient p ON pe.Patient_Key =3D p.Patient_Key
INNER JOIN evChildcareintakea evC ON pe.Patient_Key =3D
evC.Patient_Key
WHERE (pe.Payor_Key =3D 59)
AND p.create_date BETWEEN '1/1/07' AND '12/31/07'
GROUP BY P.Zip
Select @.center int =3D select count(distinct evC.day_care_center)
FROM Patient_Elg pe
INNER JOIN Patient p ON pe.Patient_Key =3D p.Patient_Key
INNER JOIN evChildcareintakea evC ON pe.Patient_Key =3D
evC.Patient_Key
WHERE (pe.Payor_Key =3D 59)
AND p.create_date BETWEEN '1/1/07' AND '12/31/07'
GROUP BY P.Zip
etc.
HTH|||On Wed, 30 Jan 2008 20:40:12 -0800 (PST), SB <othellomy@.yahoo.com>
wrote:
>I think you need to do each count(distinct field) separately and store
>them (maybe into a variable).
All at once or individually, if they are always grouped by the same
thing there will be no difference.
Roy Harvey
Beacon Falls, CT

Monday, March 19, 2012

Could not map ordinals

Server: Msg 7351, Level 16, State 2, Line 1
OLE DB provider 'SQLOLEDB' could not map ordinals for one
or more columns of object 'DBSCHEMA_COLUMNS'.
OLE DB error trace [OLE/DB Provider 'SQLOLEDB'
IColumnsInfo::MapColumnIDs returned 0x40eda:
[COLUMN_NAME=IS_COMPUTED ORDINAL=-1]].
I have 5 SQL 2000, Enterprise Edition, SP3 servers running
Windows 2000 Advanced Server w/SP3.
I have set up linking between each of these servers using
the sa username/password 'be made using this security
context.' They all work but one, SQL2. I can access any
other server from SQL2 but from any other server cannot
access tables on SQL2. I get the message above.
I had this before on this same server, but since then have
formatted the system, made sure all the hardware is
working correctly, installed SQL Server not using the same
system databases, and the error is back.
Anyone have ideas for me to try? I have searched
support.microsoft.com, groups.google.com, yahoo.com,
sqlservercentral.com, sqlmag.com to no avail.
Thanks,
Michelle
Please reply to the newsgroup or email me at
daxemail-microsoft'at'yahoo'dot'comI ended up calling Microsoft PSS. I received wonderful
assistance from Chandra who discovered the instcat.sql
script in the service pack did not run correctly on my
system. We backed up the master database, ran the script,
and I now have access to the linked servers.
Thanks! Hope this helps someone in the future,
Michelle
>--Original Message--
>Server: Msg 7351, Level 16, State 2, Line 1
>OLE DB provider 'SQLOLEDB' could not map ordinals for one
>or more columns of object 'DBSCHEMA_COLUMNS'.
>OLE DB error trace [OLE/DB Provider 'SQLOLEDB'
>IColumnsInfo::MapColumnIDs returned 0x40eda:
>[COLUMN_NAME=IS_COMPUTED ORDINAL=-1]].
>I have 5 SQL 2000, Enterprise Edition, SP3 servers
running
>Windows 2000 Advanced Server w/SP3.
>I have set up linking between each of these servers using
>the sa username/password 'be made using this security
>context.' They all work but one, SQL2. I can access any
>other server from SQL2 but from any other server cannot
>access tables on SQL2. I get the message above.
>I had this before on this same server, but since then
have
>formatted the system, made sure all the hardware is
>working correctly, installed SQL Server not using the
same
>system databases, and the error is back.
>Anyone have ideas for me to try? I have searched
>support.microsoft.com, groups.google.com, yahoo.com,
>sqlservercentral.com, sqlmag.com to no avail.
>Thanks,
>Michelle
>Please reply to the newsgroup or email me at
>daxemail-microsoft'at'yahoo'dot'com
>.
>

Friday, February 24, 2012

Could not create a Foreign key on 2 unique columns

Hello.
Could anyone tell me why it is not possible to create a foreign key on two columns those references on 2 columns in another table? Those 2 columns have each a unique constraint.

I have:
CREATE TABLE T_PK (ID1 INT CONSTRAINT CHK_UNIQUE1 UNIQUE,ID2 INT CONSTRAINT CHK_UNIQUE2 UNIQUE)

CREATE TABLE T_FK (ID1 INT, ID2 INT)

And I want to do:

ALTER TABLE T_FK ADD CONSTRAINT CHK_FK FOREIGN KEY (ID1, ID2) REFERENCES T_PK (ID1,ID2)

I see no reason why this is not working because always
a row in the table T_FK referencing only one row in table T_PK.

Thank you.
Have a nice day.in order for a compound FK to be declared, it must reference a compound unique key

in other words, it's not enough that ID1 and ID2 are each unique, the pair of them must be unique too|||The bigger questions are why do you have TWO unique columns in a single table, and why would you feel the need to have TWO foreign keys to the same unique record?|||Thank you for you reply.
Yes, I know that in MS Server documentation said those columns in FK must refer to A unique constraint.

My question was “why is not possible..” because mathematical it is possible to unique identify a row in table T_FK with a row in table T_PK.
I put such a question only from this logical point of view not for a need of use..
and maybe an answer could be you first question… Practically it’s no need to have 2 unique columns in the same table.|||why can a compound FK not reference two separately-unique-but-perhaps-invalid-when-combined keys?

becuase of the possibility that together, they might be invalid, i.e. not exist

a FK must refer to a unique row (this is relational integrity), and a unique row must be identifiable by a unique key (this is entity integrity)

if ID1 and ID2 are separately unique, then table1 could have rows like this --

ID1 ID2
101 205
102 206
103 207
104 208

your FK definition is not valid because it would allow {101,208} as a FK which doesn't exist as a PK, even though 101 and 208 do exist and are separately unique