Returning A Count Of Items Including Zero
Jul 23, 2005
Hi,
I have 2 tables, Mail_subject and Mail_Usage.
Mail_Subject contains the subject, body and some other bits of info.
CREATE TABLE [Waterford_MailSubject] (
[ID] [int] NOT NULL ,
[MailSubject] [nvarchar] (50) COLLATE
SQL_Latin1_General_CP1_CS_AS NULL ,
[MailCategory] [nvarchar] (50) COLLATE
SQL_Latin1_General_CP1_CS_AS NULL ,
[MailBody] [ntext] COLLATE SQL_Latin1_General_CP1_CS_AS NULL ,
[MailCreateDate] [smalldatetime] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Mail_Usage records the amount of times a certain mail was sent.
CREATE TABLE [Waterford_MailUsage] (
[ID] [int] NOT NULL ,
[RepScreenName] [nvarchar] (50) COLLATE
SQL_Latin1_General_CP1_CS_AS NULL ,
[MemberScreenName] [nvarchar] (50) COLLATE
SQL_Latin1_General_CP1_CS_AS NULL ,
[MailSubject] [nvarchar] (50) COLLATE
SQL_Latin1_General_CP1_CS_AS NULL ,
[TimeDate] [smalldatetime] NULL ,
) ON [PRIMARY]
GO
They are joined by Subject (not my idea, its a DB ive inherited).
What i need is to get the Mail Subject and the number of times that
Mail was sent. Ive Joined them using an INNER JOIN which gave me a
count of the number of times each one occoured except for Mails that
have not been used. I need to get zero as the count of Mails not
sent. Ive tried a LEFT OUTER JOIN but it didnt work either.
Can someone point out what i need to do ?
View 1 Replies
ADVERTISEMENT
May 12, 2006
I cannot find an easy way to DELETE items which are > 1 time in my table (i am working with MS SQL 2000)
idserialisOk
-------------------
2AAA1
3BBB0
5dfds0
6CCC1
7fdfd 0
8AAA0
9CCC0
I want to DELETE each Row IN
SELECT doublons.serial, Count(doublons.serial) AS 2Times
FROM doublons
GROUP BY doublons.serial
HAVING Count(doublons.serial)>1
and WHERE isOK = 0
in my exemple , after deleting, my table must look like
idserialisOk
-------------------
8AAA1
9CCC1
3BBB0
5dfds0
7fdfd0
thank you for helping
View 10 Replies
View Related
Feb 5, 2008
Hi
I know this is going to sound embarassingly obvious, but i cannot find a quick solution.
I have some data, I display that data in a table. Simple so far.
I have a table footer, which I want to display the total number of rows returned.
For example
"Total Rows Returned ="
Now I know how to get the total rows returned:
CountRows("Dataset1")
However when I try to put the two together like this:
= "Total Rows Returned =" + CountRows("Dataset1")
I just get the whole thing outputted, and no total for totalrows...
Anyone know what I am doing wrong?
View 6 Replies
View Related
Jul 20, 2005
I have a table of product orders. It contains a row for "platform" and Ineed to return how many times each platform is listed in the DBExample data for platform could be:XBOXXBOXXBOXPLAYSTATIONPLAYSTATIONGAMECUBEPLAYSTATIONI'd like the data to be returned asXBOX - 3PLAYSTATION - 3GAMECUBE - 1How would I go about doing this please?
View 1 Replies
View Related
Feb 18, 2008
Hi All,
I have a question regarding recorcounts. I have a set of records that i got after writing the sql query. The record layout is something like:
ID Amountdue
1 5
2 10
3 40
4 0
5 -6
6 230
7 -5
8 100
9 -1
10 0
I want to get the count of each amount due more than 0, less than 0 and equal to 0 all in the same query. So the result should look something like
Order PassGT0 PassLT0 PassEQ0
1 5 NULL NULL
2 NULL 3 NULL
3 NULL NULL 2
i can do 3 separate select count(*) if these were stored in a table but the result set was created using joins in the Query Analyser. I can also achieve the above result using unions with 3 separate queries with different conditions but this way i have to join the tables 3 times in each query and this is slowing down the query.
Please let me know if there is some other way i can achieve this.
Thanks
View 5 Replies
View Related
Aug 28, 2007
I have the following table
Region Table
ID
ParentID
RegionName
RestaurantTable
ID
RestaurantName
RegionID
What i tried to do is count the number of restaurants by specific regionname. My current query is
Select RegionID, RegionName, count(*) as RestaurantNo
From Region Inner Join Restaurant
On Region.ID = Restaurant.RegionID
However I only get the results below
RegionID RegionName RestaurantNO
1 A1 0
2 A1.1 2
3 A1.2 1
4 A1.3 0
Where A1.1 , A1.2, and A1.3 are children of A1 in Region table
The result is not correct due to A1 should have 3 in RestaurantNo due to it contains A1.1 , A1.2 and A1.3
Could anyone help me to solve this problem.
Thank you
View 6 Replies
View Related
Mar 30, 2015
We sell & ship packages that contain multiple items within them. The actual package (we call it the "parent item") is in the same table as the items within it ("child items"). If the record is a child item within a package, its "ParentId" field will contain the ItemId of the package.
So some sample records of a complete package would look like this:
ItemId | ParentId | Name | QtyAvailable
----------------------------------------
1 | NULL | Package A | 10
2 | 1 | Item 1 | 2
3 | 1 | Item 2 | 3
ItemId's 2 & 3 are items contained within the ItemId 1 package.
Now however, the client wants us to build a report showing all packages (all items where ParentId is NULL) however, they want to see the QtyAvailable of not only the package but the items as well (a total of 15 when using the example above), all grouped into a single line. So a sample report line would look like this:
Name | Available Qty
--------------------------
Package A | 15
Package B | 100
How can I do a SELECT statement that SUMS the "QtyAvailable" of both the parent & child items and displays them along with the package name?
View 6 Replies
View Related
Nov 5, 2015
I am try to count number of items that will result by filtering a date column (one Date column). Ex Column "Created Date" between 1-Sep-2015 To 30-Nov-2015.Â
I am unable to get any function that is getting right value. The below function return 40, however the actual value when i do manual filter and count is 132.
CountofQ1:=COUNTAX(DATESBETWEEN(DumpLoad1[Start Date],[StrtDate],[EndDate]),DumpLoad1[Start Date])
View 4 Replies
View Related
Nov 18, 2014
I want to get a count of how many PosAnswer are associated with the QuesToAsk 'List your top 5 favorite places'
This is the syntax I am using to achieve this, and it works, but wasn't sure if there was a better way (changing the data structure is unfortunately not an option in this situation). Here is my table structure
Code:
Create Table Test
(
QuesToAsk varchar(1000),
PosAnswer varchar(1000)
[Code] ....
And this is the syntax I use to get the count I am after
Code:
DECLARE @VariableName varchar(25)
DECLARE @FormattedVariableName varchar(25)
DECLARE @FieldCount int
SET @VariableName =
[Code] ....
View 5 Replies
View Related
Feb 13, 2008
Hi
I have written a stored procedure that accepts an argument which is the name of the table and the procedure returns me the number of rows in that table. It shows me the correct result but doesnt allow me to store the result in a variable. Here is the code
create procedure getRowCount
@v_table_name NVARCHAR(MAX)
as
DECLARE
@v_exec_query NVARCHAR(MAX),
@v_count BIGINT
begin
set @v_exec_query =(select 'select count(*) from ' + @v_table_name );
exec (@v_exec_query)
end
go
The above procedure is working fine. But i want to store the result in the @v_count variable. How can i do that?
Thanks and regards
Salil
View 3 Replies
View Related
Oct 8, 2014
Is there a way to allow the count () to return a 0 for the rows with a NULL value instead of not returning that row?
View 15 Replies
View Related
Mar 11, 2008
I have a table (tbl_entries) in my db that has a timestamp field (startDate). What I need to do is run a query that counts the number of records on a 15 min interval.
something like
start_date
2008-01-01 00:00:00.000
2008-01-01 00:00:00.000
2008-01-01 00:00:00.000
2008-01-01 00:01:00.000
2008-01-01 00:01:00.000
2008-01-01 00:01:00.000
2008-01-01 00:14:00.000
EVERY THING ABOVE HERE IS IN GROUP 1
2008-01-01 00:35:00.000
EVERY THING ABOVE HERE IS IN GROUP 2
2008-01-01 01:01:00.000
2008-01-01 01:03:00.000
2008-01-01 01:03:00.000
2008-01-01 01:04:00.000
EVERY THING ABOVE HERE IS IN GROUP 3
2008-01-01 01:29:00.000
EVERY THING ABOVE HERE IS IN GROUP 4
2008-01-01 01:41:00.000
EVERY THING ABOVE HERE IS IN GROUP 5
2008-01-01 02:25:00.000
2008-01-01 02:28:00.000
2008-01-01 02:31:00.000
2008-01-01 02:33:00.000
EVERY THING ABOVE HERE IS IN GROUP 6
Hope this is enough Info
View 3 Replies
View Related
Aug 10, 2015
I am doing a distinct count on a related table's column, but get an out of memory error if I run it for the entire table (works great for just a few rows when filtered down).The error I get is: "We couldn't get data from the external source.The operation has been cancelled because there is not enough memory available for the application. If using 32-bit version of the product consider upgrading.
I know I can add a related column and that works fine...but that seems to me like I've defeated the purpose, I have a good and proper lookup table, and should be able to run my query against its relationship.Here is the query and details below *Note I supplied a scaled down sample, on my actual model I receive these errors, not in the sample as it has only a few rows
List Workers Distinct Project Customers:=CALCULATE(DISTINCTCOUNT(Projects[CustomerID]),'WorkersToProjects')
Other measure which returns no errors, but included for completeness:
List Workers Projects:=CALCULATE(DISTINCTCOUNT([ProjectID]),ISBLANK(WorkersToProjects[ProjectID])=FALSE())
My goal here is to allow the user to view the workers assigned to a project, but also get counts of the workers assigned to the CUSTOMER of a project. For example, suppose we lose a customer, we want to see how many workers would be impacted by that, so a count of projects per worker is not useful there, we need to see a count of workers per project's customer (owner of project whom project work is being done for)The question being: How can I accomplish this:
1. WITHOUT adding a calculated column to WorkersToProjects (of Projects.CustomerID)
2. WITH better performance?
There must be a better way to write this DAX to still get the correct answer?*Pic of pivot table, again, the numbers are accurate but the formula used to List Workers Distinct Project Customers measure does NOT scale :( 3 count for red , the number of Projects John has and 2 count for blue, the unique customers/owners of those projects "Veridian Dynamics" and "Massive Dynamic". URL....
View 3 Replies
View Related
May 1, 2014
select top 15 count(*) as cnt, state from table
group by state
order by cnt desc
[code[...
Can the above three queries be combined into one and still be fast, if so how?What i am trying to go is an item count, by group, similar to ones Inbox in Outlook.
View 9 Replies
View Related
Apr 17, 2007
Hi: I'm try to create a stored procedure where I sum the amounts in an invoice and then store that summed amount in the Invoice record. My attempts at this have been me with the error "The multi-part identifier "items.TAX" could not be bound"Any help at correcting my procedure would be greatly appreciate. Regards,Roger Swetnam ALTER PROCEDURE [dbo].[UpdateInvoiceSummary] @Invoice_ID intAS DECLARE @Amount intBEGIN SELECT Invoice_ID, SUM(Rate * Quantity) AS Amount, SUM(PST) AS TAX FROM InvoiceItems AS items GROUP BY Invoice_ID HAVING (Invoice_ID = @Invoice_ID) Update Invoices SET Amount = items.Amount WHERE Invoice_ID =@Invoice_IDEND
View 3 Replies
View Related
Feb 25, 2015
I am struggling to come up with a set-based solution for this problem (i.e. that doesn't involve loops/cursors) ..A table contains items (identified by an ItemCode) and the set they belong to (identified by a SetId). Here is some sample data:
SetIdItemCode
1A
1B
24
28
26
310
312
410
[code]....
You can see that there are some sets that have the same members:
- 1 and 10
- 2 and 11
- 7, 8 & 9
What I want to do is identify the sets that have the same members, by giving them the same ID in another column called UniqueSetId.
View 8 Replies
View Related
Apr 10, 2015
I'm having an issue creating a report that can group & sum similar items together (I know in some ways, the requirement doesn't make sense, but it's what the client wants).
I have a table of items (i.e. products). Â In some cases, items can be components of another item (called "Kits"). Â In this scenario, we consider the kit itself, the "parent item" and the components within the kit are called "child items". Â In our Items table, we have a field called "Parent_Item_Id". Â Records for Child Items contain the Item Id of the parent. Â So a sample of my database would be the following:
ItemId | Parent_Item_Id | Name | QuantityAvailable
----------------------------------------
1 | NULL | Kit A | 10
2 | 1 | Item 1 | 2
3 | 1 | Item 2 | 3
4 | NULL | Kit B | 4
5 | 4 | Item 3 | 21
6 | NULL | Item 4 | 100
Item's 2 & 3 are child items of "Kit A", Item 5 is a child item of "Kit B" and Item 6 is just a stand alone item.
So, in my report, the client wants to see the SUM of both the kit & its components in a single line, grouped by the parent item. Â So an example of the report would be the following:
Name | Available Qty
--------------------------
Kit A | 15
Kit B | 25
Item 4 | 100
How I can setup my report to group properly?
View 6 Replies
View Related
Aug 6, 2006
With the function below, I receive this error:Error:Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 1, current count = 0.Function:Public Shared Function DeleteMesssages(ByVal UserID As String, ByVal MessageIDs As List(Of String)) As Boolean Dim bSuccess As Boolean Dim MyConnection As SqlConnection = GetConnection() Dim cmd As New SqlCommand("", MyConnection) Dim i As Integer Dim fBeginTransCalled As Boolean = False
'messagetype 1 =internal messages Try ' ' Start transaction ' MyConnection.Open() cmd.CommandText = "BEGIN TRANSACTION" cmd.ExecuteNonQuery() fBeginTransCalled = True Dim obj As Object For i = 0 To MessageIDs.Count - 1 bSuccess = False 'delete userid-message reference cmd.CommandText = "DELETE FROM tblUsersAndMessages WHERE MessageID=@MessageID AND UserID=@UserID" cmd.Parameters.Add(New SqlParameter("@UserID", UserID)) cmd.Parameters.Add(New SqlParameter("@MessageID", MessageIDs(i).ToString)) cmd.ExecuteNonQuery() 'then delete the message itself if no other user has a reference cmd.CommandText = "SELECT COUNT(*) FROM tblUsersAndMessages WHERE MessageID=@MessageID1" cmd.Parameters.Add(New SqlParameter("@MessageID1", MessageIDs(i).ToString)) obj = cmd.ExecuteScalar If ((Not (obj) Is Nothing) _ AndAlso ((TypeOf (obj) Is Integer) _ AndAlso (CType(obj, Integer) > 0))) Then 'more references exist so do not delete message Else 'this is the only reference to the message so delete it permanently cmd.CommandText = "DELETE FROM tblMessages WHERE MessageID=@MessageID2" cmd.Parameters.Add(New SqlParameter("@MessageID2", MessageIDs(i).ToString)) cmd.ExecuteNonQuery() End If Next i
' ' End transaction ' cmd.CommandText = "COMMIT TRANSACTION" cmd.ExecuteNonQuery() bSuccess = True fBeginTransCalled = False Catch ex As Exception 'LOG ERROR GlobalFunctions.ReportError("MessageDAL:DeleteMessages", ex.Message) Finally If fBeginTransCalled Then Try cmd = New SqlCommand("ROLLBACK TRANSACTION", MyConnection) cmd.ExecuteNonQuery() Catch e As System.Exception End Try End If MyConnection.Close() End Try Return bSuccess End Function
View 5 Replies
View Related
Sep 25, 2007
I am opening a simple command against a view which joins 2 tables, so that I can return a column which is defined as a tinyint in one of the tables. The SELECT looks like this:
SELECT TreatmentStatus FROM vwReferralWithAdmissionDischarge WHERE ClientNumber = 138238 AND CaseNumber = 1 AND ProviderNumber = 89
The TreatmentStatus column is a tinyint. When I execute that above SQL SELECT statement in SQL Server Management Studio (I am using SQL Server 2005) I get a value of 2. But when I execute the same SQL SELECT statement as a part of a SqlDataReader and SqlCommand, I get a return data type of integer and a value of 1.
Why?
View 5 Replies
View Related
Jan 30, 2008
Hi,I have a sql query like this select avg([mycolumn]) from data where date > '1/5/08' and date < '1/10/08' group by [mycolumn]order by [mycolumn] descIf all values within that average are numbers, I'm fine. If it's a 0 (not a null, a 0) it doesn't get averaged in. For instance, values 0,1,2 should produce an average of 1.(0+1+2)/3 = 1. But sql is returning a value as if my 0's were nulls and not factored in: (1+2)/2 = 1.5Does anyone know why this is happening and how to fix it?
View 5 Replies
View Related
Jan 30, 2008
Hi,
I have a sql query like this
select avg([mycolumn]) from data where date > '1/5/08' and date < '1/10/08'
group by [mycolumn]
order by [mycolumn] desc
If all values within that average are numbers, I'm fine. If it's a 0 (not a null, a 0) it doesn't get averaged in. For instance, values 0,1,2 should produce an average of 1.
(0+1+2)/3 = 1.
But sql is returning a value as if my 0's were nulls and not factored in:
(1+2)/2 = 1.5
Does anyone know why this is happening and how to fix it?
View 3 Replies
View Related
Dec 27, 2007
Hi,I'm trying to include a button control inside an iff where I am showing the results of a datalist. My aim is for each user listed, to show whether or not he is already a friend of the logged in user. To do this, I want to create an iff where if the user is already a friend, I will show the text "already a friend". If the user is not yet a friend, there will be a button saying "add as friend" which when clicked will execute an insert query to the database to add that user as a friend. I tried the code below, but it doesn't seem to recognize the button inside the iff. I really need a button to work if the result of the iff condition is DBNull.Value... Can anyone please help? <%#IIf(Container.DataItem("userNameIfFriend") Is DBNull.Value, "<asp:LinkButton id='addbuddy' runat='server' > Add as buddy</asp:LinkButton>", "Already buddy")%> I also tried the code below instead, but it doesn't work either, and I do not know what to include instead of true and false, since the button would only be enabled if the case was true. <asp:LinkButton id='addbuddy' runat='server' Enabled="<%#IIf(DataBinder.Eval(Container.DataItem, “userNameIfFriend�) is DBNull.Value, “True�, “False�)%>">Add as friend</asp:LinkButton> Thanks a lot.
View 6 Replies
View Related
Jun 15, 2007
Hi everybody
I have this sql which calculates the total
MY TABLE IS:
A B C
100 5 3
100 0 5
20 0 0
sql is
A - B + C as total
the result is it gives me only the total of the first row since it has values on the on the B AND C
the result is
A B C total
100 5 3 98
100 0 5
20 0 0
with no result for the last two rows.. I want to give a condition that if the value is zero or null go to the next...
thanks for any help
View 13 Replies
View Related
May 23, 2006
Collin writes "i have tried to do a query between 2 different tables that have different columns. within both these tables there is a column that has a column name different from the column name of the other table but the data within both columns is the same. i wanted a query that compares the data between the 2 tables.
Example is:
Table 1
Columns : firstname , age , id , grade.
Table 2
Columns : name, sex , school.
lets say that the data of column "firstname" of table 1 contains the same data as column "name" of table 2 and i would want to do a query that retrieves records for where data in the column "firstname" in table 1 is found in column "name" of table 2.
sql server 2000 with service pack 3 running on windows 2003 server service pack 1
Rgds,
Mr. C. "
View 2 Replies
View Related
Jun 28, 2006
I have a three server peer-to-peer replication setup that includes articles for tables and views. As I understand the BOL, scheme changes -- which I take to mean changes, amont other things, changes in the design of a table or view -- should automatically replicate to the other servers in the topology. Here are my quesitons:
When including a view as part of the publication, what is it, exactly, that is getting replicated? If all the tables supporting a given view are being replicated, and the view exists on all three boxes, whatelse, besides the view schema (and changes thereto) is being replicated?
Secondly, if in fact schema changes are replicated, why can't I modify a view that is part of a publication? When I try to make a change to such a view, I get a server timeout message, every single time. When I remove the view from the publication, I can make the modification with no trouble. What does replicating schema changes mean if I can't make changes to the schema?
Thanks for any enlightenment on this.
Randy
View 5 Replies
View Related
Apr 20, 2008
Hi all,
I am processing multiple flatfiles in the same folder using a "for each loop". Inorder to keep track of the file where the record comes from, I would like to add the full path and filename to the record that gets written to SQL.
Can anyone help me with this.
Thanks,
Dan
View 3 Replies
View Related
Jan 31, 2008
I'm using reporting services actions to execute some javascript. My javascript is quite complicated. Thus I don't want to duplicated it on each item. I've created javascript function and wan't to execute it from actions. But I can't find the way how to include my javascript code into my reports. If there's way to include it for all reports generated on reporting services server - it works fine for me.
Thanks in advance!
View 3 Replies
View Related
Jan 10, 2007
I hvae a stored procedure that has this at the end of it:
BEGIN
EXEC @ActionID = ActionInsert '', @PackageID, @AnotherID, 0, ''
END
SET NOCOUNT OFF
SELECT Something
FROM Something
Joins…..
Where Something = Something
now, ActionInsert returns a Value, and has a SELECT @ActionID at the end of the stored procedure.
What's happening, if that 2nd line that I pasted gets called, 2 result sets are being returned. How can I modify this SToredProcedure to stop returning the result set from ActionINsert?
View 2 Replies
View Related
Nov 21, 2006
Hi,
I'm trying to write a SQL SELECT statement where the phone numer ("telnr") is divided on three rows. How do I write a newline? I've tried , NEWLINE, and a few others.
Thanks in advance!
Pettrer, Sweden (VB, Sql Server, VWD Express, Asp.Net 2.0)
Code:
SelectCommand="SELECT [gID], [enamn], [fnamn], telnr1 + ' ' + telnr2 + ' ' + telnr3 As telnr, [epost] FROM...
The corresponding gridview's cell's value is
08-43 244 234 08-432
23 08-424333
and should be
08-43 244 234
08-432 23
08-424333
View 7 Replies
View Related
May 25, 2001
Hi All,
Here's my situation: I need to move several application db's to a new server. The current server is SQL 7.0 SP2, the new server will be SQL 7.0 SP3.
In order to avoid having the problems of mismatched logins and db user definitions, I'd like to restore the current master over the master that's created at install on the new server.
I was doing some testing of this by trying to restore the 7.0 SP2 master onto a SQL 7.0 DE edition and had some problems. (Obviously, this is not the exact scenario that I need to take place -- I want to restore standard edition to standard edition.)
Is restoring the master db from different service packs under 7.0 going to pose a problem? Is restoring the master db the best way to get around the logins issue when moving db's?
Thanks in advance for all replies.
View 1 Replies
View Related
Nov 30, 2000
I am trying to write a stored procedure that will automatically link a server and then run a stored proc on the newly linked server. At the end the stored proc will drop the server. I do not want a permanantly linked server due to the fact that this only has to be ran once a month, can you run a remote stored proc any other way then linking the servers?? Cheers to all who reply
View 1 Replies
View Related
Apr 21, 1999
Hi All
I have a table of students, and a table of lecturers, and I wish to use one select statement to return a list of users.
What I really need to do is something like this:
SELECT Students.UserID AS UserID, Lecturers.UserID AS UserID, Students.FullName AS FullName, Lecturers.FullName AS FullName FROM Students, Lecturers
which would (in my dream world!) produce something like:
UserID FullName
s0002131 Darren Student
s0054242 Richard Student
e13412 Michael Lecturer
x92342 Linda Lecturer
Does anyone know how I should do this? Should I be doing it in an stored proceedure and returning the record set from that? Currently I'm only using ASP and one line SQL statements, and would like to continue doing so.
View 1 Replies
View Related
Nov 14, 2007
I have one table where i want to use aggregate function for duplicate rows and also be able to select all fields to display. How would i do that?
Here is my query:
select Z, count(*)as num from Table
group by Z
having count(Z) > 1 ----- this returns 213 rows
Select Z, A,B,C,D From Table
Group By Z, A,B,C,D
Having Count(Z)>1 ----This gives me nothing
Hope I am explaining this correctly as to what I want.
Thanks,
Saru Brochu
View 3 Replies
View Related