A Question Relating To SELECT Count(*)

Jun 10, 2008

I am attempting to determine if a record for TODAY has been written.  If one, I update it.  If no records for TODAY have been created yet, I INSERT a new one.  I am basing my "if" (C#) on a Select count(*) WHERE as shown below.  My problem is that I do not know how to obtain the result.  The debugger displays a -1 as the count and the IF falls through to its companion ELSE.  Can anyone please set me straight?  Oh, I build 'TestDate' from getdate and it ends up as a str like "6/10/2008".  The Date column is also a varchar with the same kind of string as its contents.String fpsqlA = ("SELECT count(*) from DailyCounts WHERE Date = '"+testDate+ "'");

SqlCommand fpcmdA = new SqlCommand(fpsqlA, connStringDaily);fpcmdA.CommandType = CommandType.Text;

int iCount = fpcmdA.ExecuteNonQuery();SqlDataAdapter ad1 = new SqlDataAdapter(fpcmdA);

ad1.Fill(dtA);

 

//Test to see if a record for 'today' has already been written to the DailyCounts table. if (iCount <= 0)

{

View 6 Replies


ADVERTISEMENT

Combining 2 Select With Count And Datediff Into 1 Select. Need Help.

Jun 21, 2006



I have created two select clauses for counting weekdays. Is there a way to combine the two select together? I would like 1 table with two columns:

Jobs Complete Jobs completed within 5 days

10 5

-------------------------------------------------------------------------------------------------

SELECT COUNT(DATEDIFF(d, DateintoSD, SDCompleted) - DATEDIFF(ww, DateintoSD, SDCompleted) * 2) AS 'Jobs Completed within 5 days'
FROM dbo.Project
WHERE (SDCompleted > @SDCompleted) AND (SDCompleted < @SDCompleted2) AND (BusinessSector = 34) AND (req_type = 'DBB request ') AND
(DATEDIFF(d, DateintoSD, SDCompleted) - DATEDIFF(ww, DateintoSD, SDCompleted) * 2 <= 5)

---------------------------------------------------------------------------------------

Select COUNT(DATEDIFF(d, DateintoSD, SDCompleted) - DATEDIFF(ww, DateintoSD, SDCompleted) * 2) AS 'Total Jobs Completed'
From Project
WHERE (SDCompleted > @SDCompleted) AND (SDCompleted < @SDCompleted2) AND (BusinessSector = 34) AND (req_type = 'DBB request ')

View 9 Replies View Related

Relating Two Tables Using PK And UK

Mar 18, 2013

Is it possible to relate two tables (in the same db) using the PK (int) from one table to a UK (int, allownulls=No) from another?

I've tried, but had no success. Both tables are empty, so there is no way of having a null in the UK column that would prevent relating it to a PK. Just wanted to know if such relation is even possible before spending additional time on figuring out how to do it...

View 14 Replies View Related

Relating Tables From Different Databases

Nov 29, 2006

Hi,

I am trying to relate two tables but both are from different databases. I have a database 'Current' which has a table 'case' and another database 'Org' which has a table 'employee'. I want to establish a one-to-many relationship between employee and case. I created a coulmn 'employee_key' in the case table & entered values matching the pkey of the employee table. Then I wrote a query using joins to access the table records.

select Org..employee.pkey, Current..case.assignedengineer, Current..case.pkey from Current..case join Org..employee on Current..request.employee_key=Org..employee.pkey

Although the above query works fine, there is no relation between the two tables of the two databases, I wanted to know if this is the right way to achieve what i want to or is there a way in which i can actually create a relationship between tables of two different datbases. Can anyone suggest/help???
Also, I wanted to know if i can relate 1 table of SQL Server db with another table of Oracle DB. Please help ...........
Thanks

View 1 Replies View Related

Question Relating Conversion And Calculations

Nov 27, 2007

Hi,
  I have couple of DBF files.. and when i get them into my scrub database the datatype for all the fields in char. but after i scrub the data i put them into a money feild.. so that if so that i can do any calculations that i want in the report...
Suppose if i keep as a char or varchar in my production database... is it possible to any calculation on it in my report.. just simple additions... and if yes... do i need to convert them into anything before doing the additions... The reason i am asking this is Some of the fields in the scrub database are empty and i want to keep them the same in my production database instead of showing 0.00 as a default.
Any help will be appreciated.
Regards
Karen

View 1 Replies View Related

Problem Relating Combining Strings

May 9, 2008

hello experts
i have two sql select statements that selects data from two different tables. I want to concatenate these two sql queries into one singl query (through programming only not through joins). After concatenation i want to sent the single created query to my transection function so that it can select data from two different tables.
How can i acomplish this in vb .net or c#
thanks
fine regards
ali

View 2 Replies View Related

Question Relating To Table Size

Apr 9, 2008

Hi all,

I am still relatively new to the SQL world, and have just started looking at purging data from my databases which is older than 8 years old. I am using a routine from another forum on here to get a before Table size pre purge, and then running it again to get the new size after.

The thing i have found is that even though i have deleted over 1.5 million rows, there is actually no difference in the table size.

I have been looking at the UPDATE STATISTICS on the msdn web pages to see if i need to run this to update the information i am using for size comparisons, but it doesnt really tell me if this is one of the things that it updates, and was wondering if i was being dumb and missing something completely obvious here. The other thing i can think of is that even though the data has been deleted, the space has been retained in the indexes on the tables, and until i do a re-index i will not realise the space savings?

Many thanks in advance, and feel free to point and snigger if i have just missed something staring me in the face

Mark

View 1 Replies View Related

Relating The Field Name Use As Data In Other Table

Aug 13, 2007

hi!

i have some what a definition table of the fields of the other table
name as DefinitionTable with data as follows

FieldType FieldName1 FieldDesc TxtColor FontStyle
8 FIELD1 ABC #1111 [fsbold]
8 FIELD2 CDE #2222 [fsitalic]
8 FIELD3 EFG #3333 [fsbold]


OrigTable

OrigKey FieldType FIELD1 FIEDL2 FIELD3 Results
1 8 test1 test2 test3 ok


so the e.g. FIELD1 is a data in DefinitionTable and a field name in OrigTable..

my problem is how to get the TxtColor in merging this table.. my sp in fetching the data but only the fielddescription is


create procedure Definition
@SearchKey int,
@FieldTypeint
as
begin
DECLARE @FieldName varchar(10),
@FieldDesc varchar(30),
@TextColor int,
@mysql varchar(4000)
SET NOCOUNT ON


SELECT @mysql = 'select o.origkey, '

DECLARE MyCursor CURSOR READ_ONLY FOR
SELECT FieldName1, FieldDesc FROM DefinitionTable
WHERE FieldType = @ResultType

Open MyCursor
FETCH NEXT FROM MyCursor INTO @FieldName, @FieldDesc
WHILE @@FETCH_STATUS = 0
BEGIN
select @mysql = @mysql + 'o.' + @FieldName + ' as ' + @FieldDesc + ', '
FETCH NEXT FROM MyCursor INTO @FieldName, @FieldDesc
END

CLOSE MyCursor
DEALLOCATE MyCursor

select @mysql = @mysql + ' o.results from OrigTable o where
FieldType = ' + @ResultType

execute(@mysql)

end



the result is Ok as

OrigKey ABC CDE EFG Result
8 test1 test2 test3 ok


But the problem is how to include the TxtColor or concatenate TxtColor with this output below

OrigKey ABC CDE EFG Result
8 test1+##1111 test2+#222 test3+#3333 ok



thanx,
mygt

View 1 Replies View Related

Select Statement With Count Within Another Select

Aug 23, 2013

I am using three tables in this query, one is events_detail, one is events_summary, the third if gifts. The original select statement counted the number of ids (event_details.id_number) that appear per event_name (event_summary.event_name).

Now, I would like to add in another column that counts the number of IDs that gave a gift who attended an event that were also listed in the event_ details table. So far I have come up with the following. My main issue is linking the subquery properly back to the main query. how to count in the sub-query and have the result placed within the groups results in the main query.

SELECT es.event_name, es.event_id, COUNT(ed.id_number) Number_Attendees,
(
SELECT COUNT(gifts.donor_id) AS Count2
FROM gifts
WHERE gifts.donor_id = ed.id_number
) subquery2

[code]....

View 1 Replies View Related

Design Question Relating To A Financial Application

May 20, 2008

EDIT: Please skip over this and go to the 2nd post. After writing this, I realized it may be too complicated to comprehend, so I tried to simplify with another example which is found in the 2nd post. Or if you want you can read this one and try to understand it.


I would like to go over a design we came up with to handle a certain reporting requirement from an OLAP cube to see if this is a good approach. Also, I would like to hear about other designs that we can consider.

Here is the condensed version of the requirement.

We are measuring the performance of a bunch of portfolios. So among other dimensions, we have a portfolio dimension that holds the list of portfolios we are tracking. In a typical portfolio analysis, an analyst almost always looks at a portfolio's measures along side a benchmark portfolio's measures. A benchmark is another portfolio against which a selected portfolio is compared. So, for a given portfolio, there is a determined benchmark portfolio.

For example, an analyst might want to look at a measure called Annual_Yield for a portfolio called Portfolio_A. There will be an attribute on the member Portfolio_A that tells us what its benchark portfolio is. That attribute will basically be another member from the portfolio dimension. So, as a function of what an analyst chooses as the first portfolio (the subject portfolio), the cube should be smart enought to know what to select as the second portfolio (the benchmark portfolio).

To implement this, I am proposing the following structure for the table that will create the portfolio dimension.

PortfolioID, PortfolioName, Attr1, Attr2, ..., AttrN, BenchMarkID
1, Portfolio_A, blah, blah, ...., blah, 3
2, Porfolio_B, blah, blah, ...., blah, 3
3, Portfolio_C, blah, blah, ...., blah, null
4, Portfolio_D, blah, blah, ...., blah, 3
5, Portfolio_E, blah, blah, ...., blah, 6
6, Portfolio_F, blah, blah, ...., blah, null

So, the above data says that Portfolios A, B, and D uses Portfolio C as their benchmarks. And Portfolio E uses Portfolio F as its benchmark. Lastly, if a portfolio is used as a benchmark for other portfolios, then its BenchmarkID is null, meaning it doesn't get compared to anything, thus Portfolios C and F have null BenchmarkIDs. With this data, I would create a hierarchy in the portfolio dimension that has two levels. At the top level, there will be a portfolio and if that portfolio has a benchmark, then it will drill down to it.

With a portfolio dimension designed as such, I envision a fact table that looks like the following.

PortfolioID, SomeOtherDimIDs,....., Annual_Yield
1, , blah, ,....., 10%
2, , blah, ,....., 7%
3, , blah, ,....., 0%
4, , blah, ,....., 15%
5, , blah, ,....., 20%
6, , blah, ,....., 9%

So, going back to the original report which was looking at Annual_Yield by Portfolio_A, I would do an MDX statement such as

With Set [PortfolioAndBenchmark] As
DESCEDANTS(Portfolio_A)

Select
[Annual_Yield], [PortfolioAndBenchmark] On Columns,
Whatever Other Dimension On Rows
From
[Cube]

Does this make sense? The only concern I have is that I don't want the measures to aggregate along the portfolio hierarchy.





View 1 Replies View Related

Questions Relating To Setting Up Web Server For RDA Data Transfer

Nov 23, 2007

Our mobile application using VS2005 with VB.net is ready and we are trying to set up the SQL CE on the server to test the remote connection procedures. Sql 2005 is based on a dedicated server and is accessed via the Web server which does not have Sql installed on it. We have installed the Sql Server Me Server Tools on the Web server and configured the Virtual directory with IIS. What we cannot get our heads around is how we link the database on the separate Sql server via the web server. When the Pda contacts the Web server via IIS we somehow need to redirect to the dedicated Sql server as it cannot be contacted outside of our network. We have been told that Sql Ce can link with an existing Sql 2005 database, how can we do this?

View 6 Replies View Related

SSIS Erros Relating To Maintenance Plan Creation

Apr 2, 2006

I've been searching everywhere for a solution to this problem and no answers exist anywhere. When I try to create a new maintenance plan I get the following error. I've been told it may be related to SSIS but nobody has a solution. How do I fix this issue so I can create a maintenance plan.



Exception has been thrown by the target of an invocation. (mscorlib)
ADDITIONAL INFORMATION:
An OLE DB error 0x80004005 (Client unable to establish connection) occurred while enumerating packages. A SQL statement was issued
and failed.
An OLE DB error 0x80004005 (Client unable to establish connection) occurred while enumerating packages. A SQL statement was issued
and failed.

View 1 Replies View Related

Analysis :: Relating Multiple Fact Tables To Find Data That Exists In One But Not The Other

Nov 18, 2015

I'm currently setting up a Tabular Model to do some research between several fact tables.  In this example i have two fact tables (table 1 and table 2) which I've created a 1 to 1 relationship on phone number.  Typically I create a relationship between these tables to find common data between the two.  However, in this case I am trying to figure out the best way to model the data so that I can easily surface data from one table that does not exist in the other.  I would liken this to a LEFT JOIN or a WHERE NOT EXISTS in SQL.

Table 1 has all of the data and Table 2 Only has a subset of the data from Table 1.  What I'm trying to do here is display what attributes in Table 1 may play a part in records not existing in Table 2. What is the best way to model this?

View 3 Replies View Related

Select Count

Oct 25, 2007

 Hello, I would like to count the number of items in a table. I used the following code:1 Dim Comments As Integer
2 Dim cnn As New SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString1").ToString())
3 Dim SqlCommand As New SqlCommand("SELECT COUNT(CommentID) FROM Comments WHERE ThemeID = '3', cnn")
4
5 cnn.Open()
6 Comments = SqlCommand.ExecuteScalar()
7 cnn.Close()
 But this only gives me the error message "ExecuteScalar: Connection property has not been initialized." Can anyone help me with this? Thanks 

View 1 Replies View Related

Select Count

Nov 18, 2007

I need to select total number of rows from my data base table....here is what ive been trying....I know it wrong...but maybe someone can fix it. Thank you very much.
Function DBConnection(ByVal strUserName As String, ByVal strPassword As String) As BooleanDim MyConn As New Data.SqlClient.SqlConnection(ConnectionString)
Dim cmd As New Data.SqlClient.SqlCommand("Select count * from ClassifiedAds", MyConn)Dim dr As Data.SqlClient.SqlDataReader
'cmd.Parameters.Add(New Data.SqlClient.SqlParameter("@UserName", textbox_username.Text))
' cmd.Parameters.Add(New Data.SqlClient.SqlParameter("@Password", textbox_password.Text))
cmd.Connection.Open()
dr = cmd.ExecuteReader()
dr.Read()
If dr.HasRows Then
Label_totalclassifieds.Text = dr.Read
Return True
Else
dr.Close()
cmd.Connection.Close()
Return False
End If
End Function

View 8 Replies View Related

Select Count(*)

Mar 14, 2008

I have sql statement like "select count(*) from table where id = 1", and I want to assign the result to label.text. How do I do that? Thanks.

View 7 Replies View Related

Count() And Sub-select

Aug 26, 2004

Hello,

I'm new to SQL.
For a statistic application, I wish know the subtotal of lines pro region (Mitte, ost, west, ost, etc).

How can I do that?

A lot of thx for your help and time,
Regards, Dominique



Code:


SELECT
distinct case
when ANZSUCHEN.KANTON = '' then 'nicht_zugeteilt'
when ANZSUCHEN.KANTON = '----------------------------------' then 'nicht_zugeteilt'
when ANZSUCHEN.KANTON = 'AG' then 'mitte'
when ANZSUCHEN.KANTON = 'AI' then 'ost'
when ANZSUCHEN.KANTON = 'AR' then 'ost'
when ANZSUCHEN.KANTON = 'BE' then 'bern'
when ANZSUCHEN.KANTON = 'BL' then 'mitte'
when ANZSUCHEN.KANTON = 'BS' then 'mitte'
when ANZSUCHEN.KANTON = 'FR' then 'west'
when ANZSUCHEN.KANTON = 'GE' then 'west'
when ANZSUCHEN.KANTON = 'GL' then 'ost'
when ANZSUCHEN.KANTON = 'GR' then 'ost'
when ANZSUCHEN.KANTON = 'JU' then 'west'
when ANZSUCHEN.KANTON = 'LU' then 'mitte'
when ANZSUCHEN.KANTON = 'NE' then 'west'
when ANZSUCHEN.KANTON = 'NW' then 'mitte'
when ANZSUCHEN.KANTON = 'OW' then 'mitte'
when ANZSUCHEN.KANTON = 'SG' then 'ost'
when ANZSUCHEN.KANTON = 'SH' then 'ost'
when ANZSUCHEN.KANTON = 'SO' then 'mitte'
when ANZSUCHEN.KANTON = 'SZ' then 'mitte'
when ANZSUCHEN.KANTON = 'TG' then 'ost'
when ANZSUCHEN.KANTON = 'TI' then 'west'
when ANZSUCHEN.KANTON = 'UR' then 'mitte'
when ANZSUCHEN.KANTON = 'VD' then 'west'
when ANZSUCHEN.KANTON = 'VS' then 'west'
when ANZSUCHEN.KANTON = 'ZG' then 'mitte'
when ANZSUCHEN.KANTON = 'ZH' then 'ost'
end as region,
(SELECT count(*) FROM ANZSUCHEN WHERE ANZSUCHEN.KANTON = 'FR')
FROM
ANZSUCHEN
GROUP BY
ANZSUCHEN.KANTON
ORDER BY
region



Results:

Code:


region (No colomn name)
bern34
mitte34
nicht_zugeteilt34
ost34
west34

View 3 Replies View Related

Please Help On Select COUNT

May 3, 2007

I have the following code in VB.Net trying to count # of records in the datatable. Upon execution of the code, it returns only 1 record. I know for fact that there are more than 1 record in the datatable (there are 230 records in the table).

Can somone please tell me where is my problem ?
Public Function Get_Record_Count(ByVal Table_Name As String, ByVal Criteria As String) As Long
Dim tbl As DataTable

strSQL = "SELECT count(*) FROM [" & Table_Name & "]"
If Len(Criteria) > 0 Then
strSQL &= " WHERE " & Criteria
End If

ADO_Adapter = New OleDb.OleDbDataAdapter()
tbl = New DataTable(Table_Name)
ADO_Adapter.SelectCommand = New OleDbCommand(strSQL, ADO_Conn)

Dim Builder As OleDbCommandBuilder = New OleDbCommandBuilder(ADO_Adapter)

ADO_Adapter.Fill(tbl)
'Return # of records found in table
Get_Record_Count = tbl.Rows.Count.ToString
tbl.Dispose()

End Function

View 1 Replies View Related

SELECT COUNT...

Jan 9, 2008

Hallo!
I have a table student(teacherID, studentID, studentName...) that contains data for a certain student and a table teacher(teacherID, teacherName...) that contains data for the teacher. Student can be imagine as follow:

tID | sID ... other fields
----------
1 1
1 2
1 3
1 4
2 5
2 6
2 7
3 8

For example, teacher of tID=1 teachs to 4 students.
I'd like to select all the fields from teacher where the teacher has more than x students.
Is it possible? How can I do?
Thank you!

View 16 Replies View Related

Select Count Help

Feb 4, 2008

I am having trouble creating a query which will list schools with ALL their Admission = Null. For example, if at least one record is not null, don't list it, but as long as ALL the records have Admission = Null, then list it. I hope that's clear. Thanks!

SchoolTable:

SchoolName | ApplicantName | Admission
------------------------------------------------
North School | Student1 | Admitted
North School | Student2 |
North School | Student3 |
East School | Student4 |
East School | Student5 |
East School | Student6 |
West School | Student7 | Admitted
West School | Student8 |

Results:
SchoolName
------------
East School

View 5 Replies View Related

Select Rows Where Row Count &> 3

Jan 4, 2007

I have a view that I want to find all the rows that have a matching itemid and have more than 3 rows in them and group them by the itemid.
 I am not quite sure how to do this.
 Any ideas?
 ~mike~

View 5 Replies View Related

Select Count Issue

Oct 18, 2007

Hello,We have a database filled with local restaurants for a directory. What I'm trying to do is display a list of all the cuisines and the number of restaurants who serve that type of cuisine in parentheses. It should look like the example below:American (12)Chinese (3)Italian (5)...Here are the tables with only the relevant columns: restaurants---------------...cuisine_id... cuisines-----------cuisine_idcuisine_name... So basically I want to pull all the names from the cuisines table and then the restaurant count from the restaurants table. The only way I can think of doing that is to grab the cuisine_ids, put them in an array and then use that in a loop to get the count from the restaurants table. That's not very elegant. Is there a better way?Thank you  

View 3 Replies View Related

Trying To Get A Count In A Select Statement

Oct 21, 2007

When I try and execute this query I get the belwo error.
I want to get the ItemName and the Count as one column.
How can this be done? 
SELECT itemName, itemName +' - '+ COUNT(itemName) AS itemNameCount FROM tblItems GROUP BY itemName
ERROR: Conversion failed when converting the nvarchar value 'Spark Plug - ' to data type int.

View 3 Replies View Related

Select Count(*) For Getting # Of Records

Nov 23, 2007

Hello,
I am writing a piece of code in ASP.NET and I'd like to get the # of records on a table and used this code:
Dim ConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='G:Aco ProntoBSCBSC_v1.mdb'"Dim Con As New OleDbConnection(ConnString)
Dim Cmd As New OleDbCommand("SELECT COUNT(*) AS Expr1 FROM Metricas", Con)Dim reader As OleDbDataReader
Con.Open()
reader = Cmd.ExecuteReader()Dim NumMetr As Integer = Val(reader("Expr1"))
reader.Close()
Con.Close()
 
I am getting an error that that's no data in the table.
Any suggestions?

View 1 Replies View Related

COUNT ( FROM Nested SELECT)

Feb 25, 2008

 HI All, I have what is most likely a simple MS SQL query problem (2005).I need to add two computed columns to a result set, both of those columns are required to provide the count of a query that contains a parmamter. (The id of a row in the result set) 3 Tables (Showing only the keys)t_Sessions-> SessionID (Unique) t_SessionActivity-> SessionID (*)-> ErrorID (Unique) t_SessionErrors-> ErrorID (1) I need to return something like (Be warned the following is garbage, hopefully you can decifer my ramblings and suggest how this can actualy be done) SELECT SessionID,     (SELECT COUNT(1) AS "Activities" FROM t_SessionActivity WHERE t_SessionActivity.SessionID = t_Sessions.SessionID),     (SELECT COUNT(1) AS "Errors" FROM  dbo.t_Sessions INNER JOIN                      dbo.t_SessionActivity ON dbo.t_Sessions.SessionID = dbo.t_SessionActivity.SessionID INNER JOIN                      dbo.t_SessionErrors ON dbo.t_SessionActivity.ErrorID = dbo.t_SessionErrors.ErrorID WHERE  t_SessionActivity.SessionID = t_Sessions.SessionID)FROM t_Sessions Any help greatfully received. Thanks   

View 4 Replies View Related

Select And Count From Related MS SQL DB

Mar 8, 2006

Plz help me out making a SELECT for my imagegallery.
Table one: [albums] contains the fields [albumId], [albumTitle] and [albumDesc] - the name says it all.
Table two: [images] contains the fields [imageId], [imagePath] and forign key [albumId}
In my albumspage i would like to show all albums listed in [albums] (the easy part) AND for every album i would like to count how many images there's related to the particular album AND a random retrieve a random [imagePath]
To extract the albums something like this works: SELECT * FROM [albums] ORDER BY [albumTitle]
To count the images in a sertain album this works: SELECT COUNT(*) AS imagesCount WHERE [albumId] = ...the albumId from the album-select
And to retrieve a random imagePath this works fine: SELECT TOP 1 [imagePath] FROM [images] WHERE [imageId] = NEWID()
-But how do i combine them so that i can retrieve the data in one request? Suppose theres going to be some JOIN and group but i cant figure it out. Please help me out.

View 4 Replies View Related

SELECT COUNT Of MAX (GROUP BY)

Jul 16, 2006

Hello

I want to get the COUNT of


SELECT MAX(id) AS ids, Name, Version, Pack, Serial
FROM Products
GROUP BY Name, Version, Pack, Serial


SELECT COUNT(MAX(id) AS ids) AS countIds, Name, Version, Pack, Serial
FROM Products
GROUP BY Name, Version, Pack, Serial

doesnt work

thank you

View 4 Replies View Related

SELECT COUNT Of DISTINCT

Jul 19, 2006

helloi want to do only one query for :SELECT DISTINCT Name FROM UsersSELECT COUNT(Name) AS Names FROM Users WHERE (Name LIKE 'xxx')something like :SELECT Name, COUNT(Name) AS Names FROM Users WHERE Name IN (SELECT DISTINCT Name FROM Users)i must get :Joe 23julie 17.....thank you

View 3 Replies View Related

How To Return 1 If Select Count(*) Is &> 0

Apr 23, 2008

I'm ashamed! I'm stuck on something so simple....

I want to return a value of 1 if count(*)>0 AND 0 if COUNT(*) is 0

I have currently have this below, but isn't there a better way?

SELECT cnt=CASE WHEN (SELECT COUNT(*) FROM MyTable)>0 THEN 1 ELSE 0 END

(The full code is rather more complex than this, but the problem is the same)

Any suggestions welcome.

Cheers!
Mark

View 5 Replies View Related

Help With SELECT Query With COUNT

Jun 11, 2008

Here's my tables:

-------------------------------------------------------
tblMembers
-------------------------------------------------------
MemberID | CountryID
-------------------------------------------------------


-------------------------------------------------------
tblCountries
-------------------------------------------------------
CountryID | CountryName
-------------------------------------------------------


-------------------------------------------------------
tblOrders
-------------------------------------------------------
OrderID | MemberID | OrderTypeID
-------------------------------------------------------


-------------------------------------------------------
tblSubscriptionOrders
-------------------------------------------------------
SubscriptionOrderID | OrderID | SubscriptionPackID
-------------------------------------------------------


-------------------------------------------------------
tblSubscriptionPacks
-------------------------------------------------------
SubscriptionPackID | TypeID
-------------------------------------------------------



Here's what I'm trying to do:
1. Output each country in one column
2. Output the number of subscriptions made from a member of that country where tblOrders.orderTypeID = 3 and tblSubscriptionPacks.TypeID = 1 in the next column
3. Output the number of subscriptions made from a member of that country where tblOrders.orderTypeID = 3 and tblSubscriptionPacks.TypeID = 2 in the next column


My problem was that I was doing joins, and I was somehow ending up with orders where the OrderTypeID was NOT equal to 3, even though I declared it specifically in the WHERE clause.

Can someone help me with this query?

View 4 Replies View Related

How To Get Count Of Another Table In A Select

Nov 5, 2014

I have two tables. Houses and Guests. The guests are the people who visited the houses tied by the HouseNo.

I want to list all of the houses which has HouseName, Address, HouseNo. Then I want to show a column for the number of guests who visited it.

The Guest table has GuestName and HouseNo. How can I do a select on all houses and then show a column of COUNT(GuestName) for all the guests with the HouseNo matching each row?

View 1 Replies View Related

Using A Count W/in A Sub Select Statement

Mar 2, 2006

I'm trying to create a DTS package that uses CDO to send users an email. I need to create a sql query that counts two columns. I also need to create aliases for these two columns and then reference this in the sendEmail function. I have something that looks like this but I'm getting a DTS error. I think that it's because I'm not using an alias to reference Valid and Invalid. Can someone tell me how to alias the subselect columns correctly?? thanks :)

select advertiseremail, accountnumber from miamiherald where AdvertiserEmail is not null (select Valid = (select count (*) from miamiherald where validad = 1), Invalid = (select count (*) as Invalid from miamiherald where validad = 0))

View 1 Replies View Related

Get Count From Union Select

Jul 20, 2005

Hi,I'm trying to get the count of rows from the union of several tables.My code is:select count(*) from (select * from #AdvSearch_Mainunionselect * from #AdvSearch_Atty)This will not get past the syntax check saying that the error occurs onthe final closing ")".Can someone tell me how to correctly write this?Thanks,Glen--------------------------Numbers 6:24-26----------------------------------------------------Numbers 6:24-26--------------------------*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved