Showing posts with label write. Show all posts
Showing posts with label write. Show all posts

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 Of Given Value

Hello All,

I have a question that has been vexing me for some time now. It keeps coming up when I'm trying to write queries for SSRS reports. Lets say I have a table that has 3 columns to keep track of people's gender in a annonomys survay (very basic example):

Month (varchar) | Year (smallint) | Gender (bool)

I want to return a dataset that is grouped by Month and Year and that contains a count of each Gender which would look something like this:

Month | Year | [Male Count] | [Female Count]

January | 2006 | 100 | 120
February | 2006 | 130 | 110
March | 2006 | 120 | 145
April | 2006 | 105 | 125

How would I acheive a dataset like this? Is it possible? Do I need to join the table to itself? If so do I use an Inner Join, an Outer Join, or a Left/Right Join? Any help would be extremely appreciated.

Thanks!

Tennyson

There are several possibilities. One option:

SELECT [Month], [Year],
COUNT(CASE WHEN Gender = 0 THEN 1 END) AS MaleCount,
COUNT(CASE WHEN Gender = 1 THEN 1 END) AS FemaleCount
FROM YourSurveyTable

GROUP BY [Month], [Year]

-Sue

|||

Thank you Sue! Your help was much appreciated.

Thanks,

Tennyson

Count Occurances Of Given Value

Hello All,

I have a question that has been vexing me for some time now. It keeps coming up when I'm trying to write queries for SSRS reports. Lets say I have a table that has 3 columns to keep track of people's gender in a annonomys survay (very basic example):

Month (varchar) | Year (smallint) | Gender (bool)

I want to return a dataset that is grouped by Month and Year and that contains a count of each Gender which would look something like this:

Month | Year | [Male Count] | [Female Count]

January | 2006 | 100 | 120
February | 2006 | 130 | 110
March | 2006 | 120 | 145
April | 2006 | 105 | 125

How would I acheive a dataset like this? Is it possible? Do I need to join the table to itself? If so do I use an Inner Join, an Outer Join, or a Left/Right Join? Any help would be extremely appreciated.

Thanks!

Tennyson

There are several possibilities. One option:

SELECT [Month], [Year],
COUNT(CASE WHEN Gender = 0 THEN 1 END) AS MaleCount,
COUNT(CASE WHEN Gender = 1 THEN 1 END) AS FemaleCount
FROM YourSurveyTable

GROUP BY [Month], [Year]

-Sue

|||

Thank you Sue! Your help was much appreciated.

Thanks,

Tennyson

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

Thursday, March 22, 2012

Count All Things Happened Today

Ive got a table of notes people have created, with a field called "timecreated" which has a default value of "GETDATE()" Im trying to write an SQL statement that will count up all of the notes that people have created today/ yesturday etc. i could do it if the timecreated value was a "short date string" styled date, but its set up like : 11/11/2007 18:51:46 is there way of converting it before counting? if theres a simple way of doing this i would appricate any help thanks John

check out the year, month and day or datepart functions in t-sql.

You can assemble the date anyway you want.

|||

forgot to add:

SET DATEFORMAT

CONVERT


|||

i found this : http://support.microsoft.com/kb/q186265/

which helps me get stuff like secounds etc :

 Ms for Milliseconds
Yy for Year
Qq for Quarter of the Year
Mm for Month
Dy for the Day of the Year
Dd for Day of the Month
Wk for Week
Dw for the Day of the Week
Hh for Hour
Mi for Minute
Ss for Second

how do i get it as a short date string, like "11/10/2007" please John

|||

Try this:

WHERE timecreated>=DATEADD(dd,DATEDIFF(dd, 0,GETDATE()), 0)AND timecreated<DATEADD(dd,DATEDIFF(dd, 0,GETDATE()), 1)

|||

that worked perfectly, is it "read" by like this :

WHERE TimeCreated is equalto or greater than today + 0 days. AND TimeCreated is LessThan today + 1day.

just wondering becuase i wish to adjust this code to count things happening this week / month etc.


Thanks John

|||

Both DATEADD and DATEDIFF are very useful functions to work with datetime in TSQL. You can search to find more information on these two key words. You can modify the code with the same logic to get what you want, but i have read some good articles with a lot usages for these two functions.

|||

yeh they seem to be invalueable when attempting to work with dates / times! thanks for this! John

Count

Hi,

I need to write an SQL query/code to count say E's from a certain table. I am working in SQL Server 2005 (sp2).

For example, consider the table below;

ID From 12 D 12 D 12 C 12 E 12 D 13 D 13 E 13 D 13 E 13 D 14 H 14 D 14 D 14 D 14 D

After the SQL code, I need a result like this table below: In otherwords, I wish to have E's counted if theres E else 0 for that ID.

ID Count E's 12 1 13 2 14 0

Thanks in advance.

try this

SELECT a.[ID]
, COUNT(b.[From]) AS [Count E]
FROM YourTable a LEFT OUTER JOIN
(
SELECT [ID]
. [From]
FROM YourTable
WHERE [From] = 'E'
) b ON a.[ID] = b.[ID]
GROUP BY
a.[ID]|||

This should work reliably:

Code Snippet


SET NOCOUNT ON


DECLARE @.MyTable table
( [ID] int,
[From] char(1)
)


INSERT INTO @.MyTable VALUES ( 12, 'D' )
INSERT INTO @.MyTable VALUES ( 12, 'D' )
INSERT INTO @.MyTable VALUES ( 12, 'C' )
INSERT INTO @.MyTable VALUES ( 12, 'E' )
INSERT INTO @.MyTable VALUES ( 12, 'D' )
INSERT INTO @.MyTable VALUES ( 13, 'D' )
INSERT INTO @.MyTable VALUES ( 13, 'E' )
INSERT INTO @.MyTable VALUES ( 13, 'D' )
INSERT INTO @.MyTable VALUES ( 13, 'E' )
INSERT INTO @.MyTable VALUES ( 13, 'D' )
INSERT INTO @.MyTable VALUES ( 14, 'H' )
INSERT INTO @.MyTable VALUES ( 14, 'D' )
INSERT INTO @.MyTable VALUES ( 14, 'D' )
INSERT INTO @.MyTable VALUES ( 14, 'D' )
INSERT INTO @.MyTable VALUES ( 14, 'D' )


SELECT DISTINCT
m.[ID],
[From] = isnull( dt.[From], 0 )
FROM @.MyTable m
LEFT JOIN ( SELECT
[ID],
[From] = count( [From] )
FROM @.MyTable
WHERE [From] = 'E'
GROUP BY [ID]
) dt
ON m.[ID] = dt.[ID]


ID From
-- --
12 1
13 2
14 0

I highly recommend that you avoid using Reserved words for table/column names. FROM is a HIGHLY reserved word, and can only be used by enclosing in double quotes or square brackets.

|||LOL, i haven't tested my post. arnie's post is correct.|||Depending on the distribution of data and what indexes there are on the table, this may be a better solution:

Code Snippet

SELECT
ID,
SUM(

CASE WHEN [From] = 'E'

THEN 1 ELSE 0 END

) AS [Count E's]
FROM @.MyTable
GROUP BY ID

Steve Kass
Drew University
http://www.stevekass.com
|||

You can also use "GROUP BY ALL"

SELECT
[ID],
COUNT(*) AS [Count E's]
FROM @.MyTable
WHERE [From] = 'E'
GROUP BY ALL [ID]

|||

Try using a CASE expression.

select [ID], sum(case when [From] = 'E' then 1 else 0 end) as [Count E's]

from dbo.t1

group [ID]

go

AMB

|||

Thank all.

I tried all the replies and the one that well with my data was Steve's post.

Cheers

Tuesday, March 20, 2012

Could you write a special stored procedure for me in SQL 2005?

When I execute the SQL "select TagName from Th_TagTable where IDTopic=@.IDTopic" , it return several rows such as
TagName= http://www.hothelpdesk.com

TagName= http://www.hellocw.com
TagName= http://www.supercoolbookmark.com

I hope there is a stored procedure which can join all TagName into a single string and return,
it means when I pass @.IDTopic to the stored procedure, it return "http://www.hothelpdesk.com, http://www.hellocw.com, http://www.supercoolbookmark.com"

How can write the stored procedure?

The best answer to this question is in this post: http://databases.aspfaq.com/general/how-do-i-concatenate-strings-from-a-column-into-a-single-row.html

If you are using 2005, be sure and use the FOR XML PATH solution. It does not have of the issues that the 2000 solutions did, unless you used a cursor (which is equally heinous Smile

Could you write a special stored procedure for me in SQL 2005?

Could you write a special stored procedure for me in SQL 2005?

When I execute the SQL "select TagName from Th_TagTable whereIDTopic=@.IDTopic" , it return several rows such as
TagName= Sport
TagName= New
TagName= Health

I hope there is a stored procedure which can join all TagName into a single string and return,
it means when I pass @.IDTopic to the stored procedure, it return "Sport,New,Health"

How can write the stored procedure?

Hi,

You can use the below t-sql stateents to get the desired list of tagnames. COALESCE is the key of the below script


DECLARE @.IdTopic int
SET @.IdTopic = 1

DECLARE @.str AS nvarchar(255)

SELECT
@.str = COALESCE(@.str + ', ', '') + tagname
FROM Th_TagTable (NoLock)
WHERE IdTopic = @.IdTopic

SELECT @.str

You can better create a user-defined function instead of a stored procedure to get similar values.

Check the article and sample athttp://kodyaz.com/articles/article.aspx?articleid=29 which gets the list of a book's authors.

Eralper

http://www.kodyaz.com

|||Thanks!