Need A Count Of '0', Even If Criteria Is Not Met In A Select SQL Statement
I have the following Select SQL Statement in which I get the count of the 'Code' column based upon a criteria and Group By clause:BEGIN
SELECT Code, COUNT(Code)as exprCount1a
FROM dbo.[Test]
WHERE Section = '1' and Item = 'a' GROUP BY Code ORDER BY Code
END
The results of the statement:
Code | exprCount1a
1 2
2 4
4 1
I would like the following results:
Code | exprCount1a
1 2
2 4
3 0
4 1
Note: Code ' 3 ' doesn't have any rows that meet the select count statement criteria but I still need to populate ' 0 ' in the results.
Thank you in advance
View Complete Forum Thread with Replies
Related Forum Messages:
Help With DATE Criteria In SELECT Statement
I am trying to create a SELECT statement that would allow my users to type in a date parameter like 6/25/04. My SELECT statement would then pull all entries for that date. The problem I am running into is that it seems SQL wants the date to be parameterized as between 6/25/04 and 6/25/04 11:59:30 PM. Is there any way around that? Again I would like my users to simply enter 6/25/04 and have all entries pulled. Thanks for any help.
View Replies !
SELECT Statement With Multiple Criteria That Returns The Criterion Matched
Hello: I need assistance writing a SELECT statement. I need data from a table that matches one (or more) of multiple criteria, and I need to know which of those criteria it matched. For instance, looking at the Orders table in the Northwind database, I might want all the rows with an OrderDate after Jan 1, 1997 and all the rows with a ShippedDate after June 1, 1997. Depending on which of those criteria the row matches, it should include a field stating whether it is in the result set because of its OrderDate, or its ShippedDate. One way of doing this that I've already tried is: SELECT 'OrderDate' AS [ChosenReason], Orders.*FROM OrdersWHERE OrderDate > '1-1-1997'UNIONSELECT 'ShippedDate' AS [ChosenReason], Orders.*FROM OrdersWHERE ShippedDate > '6-1-1997' In my application, scanning a table with thousands of records for five sets of criteria takes a few seconds to run, which is not acceptable to my boss. Is there a better way of doing this than with the UNION operator? Thank you
View Replies !
Trying To Get A Count In A Select Statement
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 Replies !
Help With COUNT In SELECT Statement
Could someone assist with getting the count function working correctlyin this example please. I know the count function will return all rowsthat do not have null values, but in this case I want to count all therows except those with a zero sale price, (which are unsold).The table shows works offered for sale by an artist, with a positivefigure under SalePrice indicating a sale, and I want to count thenumber sold by each auction house, and sum the sale price by auctionhouse. The table is as follows:NameSalePriceAuctionDowling12000ChristiesDowling 0ChristiesDowling10000ChristiesDowling 0ChristiesDowling 0ChristiesDowling 6000SothebysDowling 0SothebysDowling 0SothebysDowling 8000SothebysDowling 0SothebysDowling 0SothebysDowling 0SothebysWhen I run this query:SELECT MyTable.Name, Count(MyTable.Name) AS [Number],Sum(MyTable.SalePrice) AS TotalSales, MyTable.AuctionFROM MyTableGROUP BY MyTable.Name, MyTable.AuctionHAVING (((MyTable.Name)="Dowling") AND ((Sum(MyTable.SalePrice))>0));The results are:NameNumberTotalSalesAuctionDowling 5 22000 ChristiesDowling 7 14000 SothebysThe TotalSales is correct, but the Number (Count) is incorrect, as therows with zero were also included. The results should be:NameNumberTotalSalesAuctionDowling 2 22000 ChristiesDowling 2 14000 SothebysHow do I prevent the unsolds (zeros) being counted?Thanks in advance,John Furphy
View Replies !
Count(*) And Select In The Same WITH Statement
Hi, I have a query: -- main select WITH Orders AS ( SELECT ROW_Number() OVER(MyDate ASC) RowNo, ** rest o the query *** ) SELECT * FROM Orders WHERE RowNo BETWEEN 100 AND 200 ORDER BY RowNo --count of records DECLARE @COUNT INT SELECT @COUNT = COUNT(*) FROM ** the same query as above *** RETURN @COUNT In this case it can happen that when counting records there will be different number of records that it was at time of paging. Also server has to execute this query twice and the query is quite complicated means that takes time. Is there any better way to get number of rows in the same part of query with paging ? Thanks for help Przemo
View Replies !
Using A Count W/in A Sub Select Statement
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 Replies !
Count # Of Results From SELECT Statement
Hey all - VERY new to SQL so I apologize if I butcher normally trivial things :) Looking to run a query that will retrieve the number of results returned from a select statement... Currently have a LicenseID table with a Software column...the statement that works on it's own that i've got is: SELECT * FROM Software WHERE LicensesID = 2 Currently when I run that with the data so far I get 4 results returned to me...how can I add to that statement so that instead of displaying the results themselves, I just get the number 4 returned as a total number of results? Thanks all!
View Replies !
TSQL: I Want To Use A SELECT Statement With COUNT(*) AS 'name' And ORDER BY 'name'
I am very new to Transact-SQL programming and don't have a programmingbackground and was hoping that someone could point me in the rightdirection. I have a SELECT statement SELECT FIXID, COUNT(*) AS IOIsand want to ORDER BY 'IOI's'. I have been combing through the BOL, butI don't even know what topic/heading this would fall under.USE INDIISELECT FIXID, COUNT(*) AS IOIsFROM[dbo].[IOI_2005_03_03]GROUP BY FIXIDORDER BY FIXIDI know that it is a simple question, but perhaps someone could assistme.Thanks,
View Replies !
Zero Count Values Not Appearing In SELECT Statement
Hi all I have the following tables: Code Snippet CREATE TABLE #Lkp_Circle ( ID INT , Abbreviation varchar(50) ) GO CREATE TABLE #Lkp_OtherCircles ( Circle varchar(50) ) GO CREATE TABLE #Tbl_User ( ID INT, Name VARCHAR(50), IsActive bit ) GO CREATE TABLE #Tbl_UserDetails ( AssociateID INT, CircleID INT ) GO INSERT INTO #Lkp_Circle VALUES (1,'C1') INSERT INTO #Lkp_Circle VALUES (2,'C2') INSERT INTO #Lkp_Circle VALUES (3,'C3') INSERT INTO #Lkp_Circle VALUES (4,'C4') INSERT INTO #Lkp_Circle VALUES (5,'C5') INSERT INTO #Lkp_Circle VALUES (6,'C6') INSERT INTO #Lkp_Circle VALUES (7,'C7') GO INSERT INTO #Lkp_OtherCircles VALUES ('C3') INSERT INTO #Lkp_OtherCircles VALUES ('C4') INSERT INTO #Lkp_OtherCircles VALUES ('C5') INSERT INTO #Lkp_OtherCircles VALUES ('C6') GO INSERT INTO #Tbl_User VALUES ( 101,'U 1','True') INSERT INTO #Tbl_User VALUES ( 102,'U 2','True') INSERT INTO #Tbl_User VALUES ( 103,'U 3','True') INSERT INTO #Tbl_User VALUES ( 104,'U 4','True') INSERT INTO #Tbl_User VALUES ( 105,'U 5','True') GO INSERT INTO #Tbl_UserDetails VALUES(101,3) INSERT INTO #Tbl_UserDetails VALUES(102,4) INSERT INTO #Tbl_UserDetails VALUES(103,5) INSERT INTO #Tbl_UserDetails VALUES(104,5) INSERT INTO #Tbl_UserDetails VALUES(105,3) GO SELECT ISNULL(Circle,'Total') Circle, ISNULL(COUNT([HeadCount]),SUM(1)) AS [Total] FROM ( SELECT DISTINCT 'Circle' = CASE WHEN #Lkp_Circle.Abbreviation IN (SELECT Circle FROM #Lkp_OtherCircles) THEN #Lkp_Circle.Abbreviation WHEN #Lkp_Circle.Abbreviation NOT IN (SELECT Circle FROM #Lkp_OtherCircles) THEN 'Others' ELSE 'Total' END,ISNULL(#Tbl_UserDetails.AssociateID,0) AS 'HeadCount' FROM #Tbl_User INNER JOIN #Tbl_UserDetails ON #Tbl_User.ID = #Tbl_UserDetails.AssociateID INNER JOIN #Lkp_Circle ON #Tbl_UserDetails.CircleID = #Lkp_Circle.ID WHERE #Tbl_User.IsActive='True' AND #Tbl_User.ID>0 AND #Tbl_UserDetails.AssociateID>0 ) AS PivotTable GROUP BY Circle WITH Cube DROP TABLE #Tbl_User,#Tbl_UserDetails,#Lkp_Circle,#Lkp_OtherCircles ----EXPECTED RESULT --Circle HeadCount --C3 2 --C4 1 --C5 2 --C6 0 --Others 0 --Total 5 -- ----ACTUAL RESULT --Circle HeadCount --C3 2 --C4 1 --C5 2 --Total 5 The criteria for Others is that those circles which are not part of #Lkp_OtherCircles i.e. C1,C2,C3 and C7 clubbed together. I have tried checking for the condition ISNULL when for that circle there is no user but the end result is same. Can someone tell me where I am going wrong and how to correct it?
View Replies !
Cannot Construct A SELECT DISTINT COUNT... Statement In SSCE 3.1
Hi everyone, sorry to b a pest again! Before I made the decision to change the DB used in my app from SQL Server Express to SSCE, I had no problems with constructing a SELECT statement as laid out in the Title. Basically, I have 2 tables with a one-many relationship between them. In the Parent table, I had a SQL Statement as follows: SELECT DeptID, DeptName, (SELECT DISTINCT COUNT(Active) FROM Documents WHERE (Documents.DeptID = Dept.DeptID) AND (Documents.Active = 'True') AS CountOfActive FROM Dept Now in SSCE 3.1, I get an "Unable to parse query" error message when I construct the same SQL statement in my dataset designer. Any thoughts on how I may solve this? Much thanx! Shalan
View Replies !
Count Same Field Mutiple Times With Different Criteria
Is it possible to count the same field with different criteria. It would be something like this. car_table car_id car_name car_brand So you would execute a statement which would count(car_brand) with two different criteria. I am not sure if this is possible or if there is another way to approach it.
View Replies !
How To Count Cases For Different Groups Based On Different Criteria
Hello, I need to create a query that will count new cases based on the create date(create_date) and criteria for the groups(The only way to distinguish between the 2 major groups mts and bnb is area!= 'bnb" because everything else is MTS). The sample report I need to create below shows how it needs to be counted weekly, for a 4 month period, for the groups under MTS and BNB. The totals and grand totals can be achieved in the report tool. I want to create variables for the new cases (mts_newcases_sales, mts_newcases_salesd, bnb_newcases_salesd etc) Ex. MTS sales : (status = 'Calculated' OR status = 'REJECTED') and errorsource != 'marketing' and accountns is null and area != 'BNB'(everything else is MTS) MTS salesd ; Credit >= '1001' and (status = 'REJECTEDV' or status = 'ACCEPTEDS') and errorsource != 'marketing' and accountnr is null BNB creditr: Credit < 101 and (status = 'SUBMITTED' OR status = 'REJECTEDS' OR status = 'REJECTEDA' OR STATUS = 'ACCEPTEDC') 12-Jan 19-Jan 26-Jan 2-Feb 9-Feb 16-Feb MTS New Cases Received 85 84 79 98 79 95 Sales 30 32 27 40 42 38 SalesD 47 34 37 23 23 37 CreditR 44 29 26 35 55 54 CreditB 6 12 9 5 7 13 CreditS - - - - 3 - CreditP 10 11 11 24 17 7 MTS Subtotal 140 125 110 144 151 150 BNB New Cases Received 12 13 14 14 6 11 Sales - - - - - - SalesD - - - - - - CreditR 12 11 12 10 5 9 CreditB 8 13 9 17 16 6 CreditS - - 2 - - - CreditP 1 1 1 1 4 3 BNB Subtotal 21 25 24 28 26 19 Total New Cases Received 97 97 93 112 85 106 Sales 30 32 27 40 42 38 SalesD 47 34 37 23 23 37 CreditR 56 40 38 45 60 63 CreditB 14 25 18 22 23 19 CreditS - - 2 - 3 - CreditP 11 12 12 25 21 10 Grand Total 161 150 134 172 177 169 This is just a very brief bit of code SELECT MTS_new_cases_sales, mts_new_cases_salesd €¦€¦. FROM vwCreditN WHERE mts_sales_new_cases = ( )... and (status = 'Calculated' OR status = 'REJECTED')... Can you please show me how to accomplish this? Thank you in advance for your effort, Rhonda
View Replies !
Transaction Count After EXECUTE Indicates That A COMMIT Or ROLLBACK TRANSACTION Statement Is Missing. Previous Count = 1, Current Count = 0.
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 Replies !
UPDATE Statement With Multiple Criteria
I am trying write a query to update a column of data in my xLegHdr table however the update is based on multiple criteria. I was trying to use "IF..ELSE" statements but that is not working. I would like to update the "SMiles" column based on the data in the "Dist" column. If the number in the "Dist" column is less than 250 then subtract 25 and multiply it by 1.15 the result should go in the "SMiles" column. If the number is grater than 250 then subtract 40 and multiply by 1.15 and place the result in the "SMiles" column; like so: UPDATE xLegHdr SET SMiles = IF Dist<250 THEN Round(Dist-25)*1.15) ELSE Round(Dist-40)*1.15) END IF Any ideas?
View Replies !
Select Same Field Twice For Different Criteria
I need a little insight on how to select the same field from the same table, but for different criteria. here are example tables... Categories CATSUBCATNAME 10MainTitle 11SubTitle #1 12SubTitle #2 20Section 21Section #1 DataTable CATSUBCATINFO 11Detail Information for subtitle #1 12Detail information for subtitle #2 desired result would be: MainTitle, SubTitle #1, Detail Information for subtitle #1 MainTitle, SubTitle #2, Detail Information for subtitle #2 Select c1.Name, c2.Name, d.info from DataTable d, Categories c1, Categories c2 where c1.CAT = d.CAT and c2.CAT = d.CAT and c2.SUBCAT = d.SUBCAT
View Replies !
Looking For Field Name From Table On Select Criteria
Hari writes "Sub:- looking for Field name from table on select criteria dear friends I have an table [assosories] which have 100 fields. initial 10 fields have some date, varchar, int types rest 90 are bool type. for a single row I need to know the field name which have true vaules in rest 90 fields I need to insert this field name into another table as a row. Thanks HARI"
View Replies !
Select Based Upon Multiple Criteria
Hi I would like to get records from a table and present a result set based upon the search fields the search fields could be any of the following: PNo, Year, JNo, C1No6, C2No3, C3No3, C4No3, they could enter any combination of these however if they dont enter any of the above then the search should not retrieve any thing. the table colunms are listed below and asample data set is also shown below. Currently the only way i think it can be done is by writing multiple queries with different queries to be executed based upon the search field that have been filled? can it be done in a stored prcedure? and can it be done using non-dynamic sql? Name, PNo, Year, JNo, C1No6, C2No3, C3No3, C4No3, RefImage adam, 01, 1999, 099, 3yh333, 888, 989, 999, ref1999099.jpg Brian, 01, 2005, 029, 3yh323, 828, 929, 929, ref1929099.jpg sid, 04, 1989, 039, 3yh343, 838, 939, 939, ref1993399.jpg jack, 06, 1996, 069, 3yh633, 868, 969, 969, ref1669099.jpg
View Replies !
Adding Optional Criteria In A Select Proc
I would like to write 1 proc that can take additional criteria if its sent in. An example is: select HA.PriceId, HA.VendorPackageId from Criteria HA Inner Join ( select VendorPackageId from ValidVendorPackages where Vendor = @VENDOR and Sitecode = @SITECODE and PackageType = @PACKAGETYPE )HB on HA.VendorPackageId = HB.VendorPackageId and CriteriaId in ( select CriteriaID from ValidItemCriteria where Destination = @DESTINATION and LengthOfStay = @LENGTHOFSTAY and Ages = @AGE and ComponentType = @COMPONENTTYPE_1 and ValidItemType = @VALIDITEMTYPE_1 and ItemValue = @ITEMVALUE_1 ) Multiple @COMPONENTTYPE, @VALIDITEMTYPE,@ITEMVALUE can be sent in. Instead of making multiple procs or copying the proc multiple times with an if statement at the top checking the number of parameters that aren't =''. Is there a way to exectue: and CriteriaId in ( select CriteriaID from ValidItemCriteria where Destination = @DESTINATION and LengthOfStay = @LENGTHOFSTAY and Ages = @AGE and ComponentType = @COMPONENTTYPE_1 and ValidItemType = @VALIDITEMTYPE_1 and ItemValue = @ITEMVALUE_1 ) and CriteriaId in ( select CriteriaID from ValidItemCriteria where Destination = @DESTINATION and LengthOfStay = @LENGTHOFSTAY and Ages = @AGE and ComponentType = @COMPONENTTYPE_2 and ValidItemType = @VALIDITEMTYPE_2 and ItemValue = @ITEMVALUE_2 ) and CriteriaId in ( select CriteriaID from ValidItemCriteria where Destination = @DESTINATION and LengthOfStay = @LENGTHOFSTAY and Ages = @AGE and ComponentType = @COMPONENTTYPE_3 and ValidItemType = @VALIDITEMTYPE_3 and ItemValue = @ITEMVALUE_3 ) Ignoring the 2nd 2 selects if @COMPONENTTYPE_2, @VALIDITEMTYPE_2,@ITEMVALUE_2 and @COMPONENTTYPE_3, @VALIDITEMTYPE_3,@ITEMVALUE_3 are = '' Thanks for your help in advance.
View Replies !
Aggregate Multiple Columns With Different SELECT Criteria
Let me start with saying thanks to all of you who have helped me (I'm a SQL newbee after doing OO for the past 12+ years) I need to do several aggregates on multiple columns, with each column having different SELECT Criteria. Sample Data: Dept Project Cost CostFlag Schedule ScheduleFlag D1 D1P1 495 1 135 3 D1 D1P2 960 2 70 2 D1 D1P3 1375 3 105 2 D1 D1P4 1050 2 160 3 D1 D1P5 1890 3 40 1 D2 D2P1 650 1 155 3 D2 D2P2 890 2 125 2 D2 D2P3 1235 3 85 1 D2 D2P4 430 1 140 3 D3 D3P1 1960 3 45 1 D3 D3P2 1490 3 85 1 D3 D3P3 1025 2 135 3 D3 D3P4 615 1 100 2 D3 D3P5 270 1 70 1 D3 D3P6 815 2 155 3 I need to calculate MEAN (average), Standard Deviation, Variance, Range, Span & Median for each data column (Cost, Schedule in the test data), where each data column has different selection criteria. I have the calculations working for each column individually (e.g. funcCalcCost, funcCalcSchedule), but I need to return the calculated values as a single data set: SELECT Dept, Project, AVG(Cost) as Cost_Mean, MAX(Cost) - MIN(Cost) as Cost_Range, ....... WHERE CostFlag = @InputParameter GROUP BY Dept, Project The code above works great - but only for a single column. I need to return a dataset like this: Dept Project Cost_Mean Cost_Range D1 D1P1 495 135 D1 D1P2 960 70 D1 D1P3 1375 105 I need to return a dataset like this: Dept Project Cost_Mean Cost_Range Schedule_Mean Schedule_Range D1 D1P1 495 135 100 28 D1 D1P2 960 70 42 12 D1 D1P3 1375 105 91 38 I also have working code calculate the MEDIAN (what a pain that was, thank god I found a code example to get me going on the MEDIAN) Thanks!
View Replies !
Select Criteria Based On Date - Cleaner Way To Write?
Code: SELECT (JUL_CURR_CREDITS + JUL_CURR_DEBITS + AUG_CURR_CREDITS + AUG_CURR_DEBITS + SEP_CURR_CREDITS + SEP_CURR_DEBITS + OCT_CURR_CREDITS + OCT_CURR_DEBITS + NOV_CURR_CREDITS + NOV_CURR_DEBITS + DEC_CURR_CREDITS + DEC_CURR_DEBITS + JAN_CURR_CREDITS + JAN_CURR_DEBITS + FEB_CURR_CREDITS + FEB_CURR_DEBITS + MAR_CURR_CREDITS + MAR_CURR_DEBITS + APR_CURR_CREDITS + APR_CURR_DEBITS + MAY_CURR_CREDITS + MAY_CURR_DEBITS + JUN_CURR_CREDITS + JUN_CURR_DEBITS) as CURR_AMT I need to sum these amounts running from July to the month prior to whatever the current month is. So if it was August, it would only be Code: SELECT (JUL_CURR_CREDITS + JUL_CURR_DEBITS) as CURR_AMT Is there a cleaner (shorter) way to iterate through the twelve months than either writing the query 12 times in an IF statement, or 12 CASE statements? This is only part of a query that joins several tables (not shown). Any suggestions on the best way to write this would be valued.
View Replies !
Select Record Based On Multiple Criteria (vars)
Hi! I'm new to SQL and have a question... I'm writing a script that gathers a few variables from an outside source, then queries a table and looks for a record that has the exact values of those variables. If the record is not found, a new record is added. If the record is found, nothing happens. Basically my SELECT statement looks something like this, then is followed by an If... Else statement SELECT * FROM TableName WHERE LastName = varLastName AND FirstName = varFirstName AND Address = varAddress If RecordSet.EOF = True Then 'Item Not Found, add new record 'code to add new record...... Else 'Item Found, do nothing End If RecordSet.Update RecordSet.Close Even when I try to delete the If.. statement and simply display the records, it comes up as blank. Is the syntax correct for my SELECT statement??
View Replies !
Select Statement Within Select Statement Makes My Query Slow....
Hello... im having a problem with my query optimization.... I have a query that looks like this: SELECT * FROM table1 WHERE location_id IN (SELECT location_id from location_table WHERE account_id = 998) it produces my desired data but it takes 3 minutes to run the query... is there any way to make this faster?... thank you so much...
View Replies !
Need Help: Count A Field Based On Field Criteria
Hi, I can't seem to get my head around this, hopefully someone can help. In my query I have a few fields, which I would like to get the number of rows based on certain criteria. For example I have a gender field, and I would like to get the number of females or males from the query. I have been trying the following method, which uses the Sum and Iif functions: Code Block Sum(IIf(Fields!gender.Value = "Female", 1, 0)) This does bring back a figure, but it's not correct. My query brings back 46 rows, yet the expression only brings back a figure of 24. I have even tried doing a query using CASE statements, bringing back just one row with all the correct figures in. But if I then add a textbox, with the expression '=Fields!gender.Value' it also brings back 24, yet the fields actual value in the query is 46. What is causing this problem? Is there a way around this? Thanks
View Replies !
Properties Row Count Not = Select Count(*)
I have a SQL2000 table, and when I display Properties, it says the row count = 927, but when I do select count(*), I get 924. I did a refresh on everything (since refresh is often needed), finally exited SQL Ent Mgr, went back in with the same result. I believe 924 is the correct count ..... Is that table corrupted somehow ? Can I trust the count in "Properties" for other tables ?
View Replies !
SQL Select Query Need For Following Criteria. Please Help, Retrieve Records With Independent Price And Its Total Volume Per Min
Time Price Volume 090048 510 6749 090122 510 2101 090135 510 1000 090204 505 2840 090213 505 220 090222 505 1260 090232 505 850 090242 505 200 090253 510 1200 090313 510 570 090343 510 250 090353 510 160 Criteria Retrieve records with independent price and its total volume per minute SELECT SUBSTRING(st,1,4) AS Ttime,d_price AS Price,SUM(l_cum) AS Volume FROM cmd4 WHERE sd='20060717' AND serial='0455' GROUP BY SUBSTRING(st,1,4),d_price,l_cum Result of the above query: - Time Price Volume 0900 510 6749 0901 510 1000 0901 510 2101 0902 505 200 0902 505 220 0902 505 850 0902 505 1260 0902 505 2840 0902 510 1200 0903 510 160 0903 510 250 0903 510 570 THE FOLLOWING RESULT STILL NOT A TOTAL FOR A MINUTE] E.G 0901 510 1000 + 0901 510 2101 = 0901 510 3101 <- I NEED THIS Can any one advice or give me tips over this. Please
View Replies !
Best Practice Question: JOIN Criteria Vs. WHERE Criteria
For example, consider the following queries: DECLARE @SomeParam INT SET @SomeParam = 44 SELECT * FROM TableA A JOIN TableB B ON A.PrimaryKeyID = B.ForeignKeyID WHERE B.SomeParamColumn = @SomeParam SELECT * FROM TableA A JOIN TableB B ON A.PrimaryKeyID = B.ForeignKeyID AND B.SomeParamColumn = @SomeParam Both of these queries return the same result set, but the first query filters the results in the WHERE clause whereas the the second query filters the results in the JOIN criteria. Once upon a time a DBA told me that I should always use the syntax of the first query (WHERE clause). Is there any truth to this, and if so, why? Thanks.
View Replies !
Combining 2 Select With Count And Datediff Into 1 Select. Need Help.
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 Replies !
Multiple Tables Used In Select Statement Makes My Update Statement Not Work?
I am currently having this problem with gridview and detailview. When I drag either onto the page and set my select statement to pick from one table and then update that data through the gridview (lets say), the update works perfectly. My problem is that the table I am pulling data from is mainly foreign keys. So in order to hide the number values of the foreign keys, I select the string value columns from the tables that contain the primary keys. I then use INNER JOIN in my SELECT so that I only get the data that pertains to the user I am looking to list and edit. I run the "test query" and everything I need shows up as I want it. I then go back to the gridview and change the fields which are foreign keys to templates. When I edit the templates I bind the field that contains the string value of the given foreign key to the template. This works great, because now the user will see string representation instead of the ID numbers that coinside with the string value. So I run my webpage and everything show up as I want it to, all the data is correct and I get no errors. I then click edit (as I have checked the "enable editing" box) and the gridview changes to edit mode. I make my changes and then select "update." When the page refreshes, and the gridview returns, the data is not updated and the original data is shown. I am sorry for so much typing, but I want to be as clear as possible with what I am doing. The only thing I can see being the issue is that when I setup my SELECT and FROM to contain fields from multiple tables, the UPDATE then does not work. When I remove all of my JOIN's and go back to foreign keys and one table the update works again. Below is what I have for my SQL statements:------------------------------------------------------------------------------------------------------------------------------------- SELECT:SELECT People.FirstName, People.LastName, People.FullName, People.PropertyID, People.InviteTypeID, People.RSVP, People.Wheelchair, Property.[House/Day Hab], InviteType.InviteTypeName FROM (InviteType INNER JOIN (Property INNER JOIN People ON Property.PropertyID = People.PropertyID) ON InviteType.InviteTypeID = People.InviteTypeID) WHERE (People.PersonID = ?)UPDATE:UPDATE [People] SET [FirstName] = ?, [LastName] = ?, [FullName] = ?, [PropertyID] = ?, [InviteTypeID] = ?, [RSVP] = ?, [Wheelchair] = ? WHERE [PersonID] = ? ---------------------------------------------------------------------------------------------------------------------------------------The only fields I want to update are in [People]. My WHERE is based on a control that I use to select a person from a drop down list. If I run the test query for the update while setting up my data source the query will update the record in the database. It is when I try to make the update from the gridview that the data is not changed. If anything is not clear please let me know and I will clarify as much as I can. This is my first project using ASP and working with databases so I am completely learning as I go. I took some database courses in college but I have never interacted with them with a web based front end. Any help will be greatly appreciated.Thank you in advance for any time, help, and/or advice you can give.Brian
View Replies !
Using Conditional Statement In Stored Prcodure To Build Select Statement
hiI need to write a stored procedure that takes input parameters,andaccording to these parameters the retrieved fields in a selectstatement are chosen.what i need to know is how to make the fields of the select statementconditional,taking in consideration that it is more than one fieldaddedfor exampleSQLStmt="select"if param1 thenSQLStmt=SQLStmt+ field1end ifif param2 thenSQLStmt=SQLStmt+ field2end if
View Replies !
TSQL - Use ORDER BY Statement Without Insertin The Field Name Into The SELECT Statement
Hi guys, I have the query below (running okay): Code Block SELECT DISTINCT Field01 AS 'Field01', Field02 AS 'Field02' FROM myTables WHERE Conditions are true ORDER BY Field01 The results are just as I need: Field01 Field02 ------------- ---------------------- 192473 8461760 192474 22810 Because other reasons. I need to modify that query to: Code Block SELECT DISTINCT Field01 AS 'Field01', Field02 AS 'Field02' INTO AuxiliaryTable FROM myTables WHERE Conditions are true ORDER BY Field01 SELECT DISTINCT [Field02] FROM AuxTable The the results are: Field02 ---------------------- 22810 8461760 And what I need is (without showing any other field): Field02 ---------------------- 8461760 22810 Is there any good suggestion? Thanks in advance for any help, Aldo.
View Replies !
SQL COUNT Statement
I am trying to count records in SQL Server. I have this Stored procedure but I am getting SQL errors. Alter Procedure usp_rptQualityReport3 As SELECT * FROM viewQualityReport SELECT COUNT([FailureReason]) AS FC WHERE (((viewQualityReport.FailureReason) <> N'NONE')) ORDER BY FC I am trying to count records that have like FailureReasons. I am selecting all the records from the view I created and then trying to count the records in the second Select statement. Basically what I want to do is counf them so I can then rank them starting with failure reasons that happen the most. I don't know what I am doing wrong.
View Replies !
Please Help With The SQL COUNT Statement!
I'm trying to run this SQL statement in my ASP code, sql="SELECT COUNT(*) FROM order_list WHERE ref_index='"&ref_index&"'" The problem is, should i create a variable to store the returned integer? I tried rs_itemcount = conn.execute(sql) and then response.write(rs_itemcount.value) But it returns with an error... any ideas how to store the integer and use it?! thx!
View Replies !
Where Statement Again A Count
I can insert into a temp table and get this to work fine but it am unable to pass my sdate and endate parameter from reporting services. This Works Fine I Just want to throw in a where statement. How do you get this to work? I tried [] () '' WHERE Cola=Count(*) = Colb=Count(DidNotAttend) Use Consumer Select TripsId.ID#, Cola=Count(*), Colb=Count(DidNotAttend) FROM Trips INNER JOIN TripsId ON Trips.Rec# = TripsId.TripId# Group by TripsId.ID#
View Replies !
How To Write Select Statement Inside CASE Statement ?
Hello friends, I want to use select statement in a CASE inside procedure. can I do it? of yes then how can i do it ? following part of the procedure clears my requirement. SELECT E.EmployeeID, CASE E.EmployeeType WHEN 1 THEN select * from Tbl1 WHEN 2 THEN select * from Tbl2 WHEN 3 THEN select * from Tbl3 END FROM EMPLOYEE E can any one help me in this? please give me a sample query. Thanks and Regards, Kiran Suthar
View Replies !
Using A Count If Within A Group By SQL Statement?
I have the following SQL Statement: SELECT CONVERT(char(10), FixtureDate, 101) AS Date, COUNT(*) AS 'NumberOfRecords'FROM tblFixturesGROUP BY CONVERT(char(10), FixtureDate, 101) I want to add a new column called "need results". This column needs to be count if a certain cell is NULL. Count If HomeScore IS NULL as well as grouping by date and counting the number of records. So the third column needs to count the number of records where homescore IS NULL
View Replies !
Trying To Count A Case Statement?
I need to get a total count of leads and then separate the counts by either Retail or Wholesale - Here's my table schema - CREATE TABLE [dbo].[Sent] ( [IdentID] [int] IDENTITY (1, 1) NOT NULL , [LeadID] [bigint] NOT NULL , [AffiliateID] [bigint] NULL , [PartnerID] [int] NULL , [FranchiseID] [bigint] NULL , [FirstName] [t_Name] NULL , [LastName] [t_LastName] NULL , [Address] [t_Address] NULL , [Zip] [t_ZipCode] NULL , [Make] [t_Make] NULL , [Model] [t_Model] NULL , [DateIn] [datetime] NULL , Here's my query - Since I'm grouping by the partnerid select distinct make, count(leadid) as TotalCount, case when PartnerID = 1 then 'retail' else 'wholesale' end as disposition from leads_sent (nolock)where datein between '2007-09-01' and '2007-09-30' group by make, partnerid order by make Here's a sample my current output - Acura 1 wholesale Acura 2 wholesale Acura 4 wholesale Acura 5 wholesale Acura 21 wholesale Acura 34 wholesale Acura 37 wholesale Acura 56 wholesale Acura 57 wholesale Acura 72 wholesale Acura 510 retail Audi 1 wholesale Audi 3 wholesale Audi 7 wholesale Audi 12 wholesale Audi 16 wholesale Audi 18 wholesale Audi 23 wholesale Here's the output I need Make Total Count RetailCount WSCount Acura 798 510 288 Audi 256 75 181
View Replies !
SQL Statement Count NULL Values
Hello,Thanks for helping me with this... I really appreciate it.I have a table called tblPatientDemographics with a number of columns.I would like to count the number of NULL values per record within mytable.tblPatientDemographicsPatientID Age Weight Height Race1234567 20 155 <NULL> Caucasian8912345 21 <NULL> <NULL> <NULL>In the first example above I want to display '1'In the second example above I want to display '3'Any help would be very much appreciated.Thanks !Chad*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!
View Replies !
SProc - Ad Hoc Sql Statement With COUNT For Exec(@SQL) ??
Hello, I need to get the count into a local variable: Select @SQL = 'Select ' + @TotalRowCount + ' = Count(*) )' + ' From ' + @TableName + ' Where ' + @WhereClause Exec(@SQL) It complains about ‘…. Integer…’, but even if I use a varchar parm and convert Count to varchar in the sql statement, it still does not work. It does not like the = , or so it says. Any help greatly appreciated, Judith
View Replies !
Help With Query (count With Case Statement)
Hi, I have the following query, that returns the proper count value I am looking for. I would like to modify it a little bit, but can't remember exactly how to do it. select count(messageFromID) FROM tblMessage WHERE messageFromID = 1000) as OutBoundMessages Basically now, it returns the "OutBoundMessages" column I would like it to return "OutboundMessages_unChecked" and "OutboundMessages_checked" as well as "OutboundMessages_total" (I guess I could determine this value by adding the two values in the front end too. I definatley dont want to do a lookup to determine the total ) I determine if the column is "checked" or "unChecked" by a column in tblMessage For example tblMessage.checked = 1 = ("checked") tblMessage.checked = 0 = ("unChecked") any help much appreciated.. thanks! mike123
View Replies !
Help With Delete Statement/converting This Select Statement.
I have 3 tables, with this relation: tblChats.WebsiteID = tblWebsite.ID tblWebsite.AccountID = tblAccount.ID I need to delete rows within tblChats where tblChats.StartTime - GETDATE() < 180 and where they are apart of @AccountID. I have this select statement that works fine, but I am having trouble converting it to a delete statement: SELECT * FROM tblChats c LEFT JOIN tblWebsites sites ON sites.ID = c.WebsiteID LEFT JOIN tblAccounts accounts on accounts.ID = sites.AccountID WHERE accounts.ID = 16 AND GETDATE() - c.StartTime > 180
View Replies !
Select Statement Problem - Group By Maybe Nested Select?
Hey guys i have a stock table and a stock type table and what i would like to do is say for every different piece of stock find out how many are available The two tables are like thisstockIDconsumableIDstockAvailableconsumableIDconsumableName So i want to,Select every consumableName in my table and then group all the stock by the consumable ID with some form of total where stockavailable = 1I should then end up with a table like thisEpson T001 - Available 6Epson T002 - Available 0Epson T003 - Available 4If anyone can help me i would be very appreciative. If you want excact table names etc then i can put that here but for now i thought i would ask how you would do it and then give it a go myself.ThanksMatt
View Replies !
Count The Number Of Rows In A UNION ALL Statement
Hi,Should be quite simple but can someone please tell me the best way tocount the number of rows in an UNION ALL statement.I tried using @@ROWCOUNT but that doesn't seem to contain the correctnumber.Also, I assume that running the query again but just returning count(*)instead of the data is horribly inefficient (plus the code is thenbloated.)?Thanks,Mark
View Replies !
SQL Statement, Adding Two COUNT/CASE Statements
SELECT COUNT(DISTINCT CASE WHEN visit_type = 0 THEN visitor_id END) AS [New Visitors], COUNT(DISTINCT CASE WHEN visit_type = 0 THEN visitor_id END) AS [Returning Visitors] FROM content_hits_tbl WHERE (hit_date BETWEEN DATEADD(mm, - 1, GETDATE()) AND GETDATE()) ======================= How do I add up both COUNT/CASE columns? Would it be: SUM([New Visitors] + [Returning Visitors]) AS Total I tried this and it doesn't work. I get invalid column names error for both. I have even tried: SUM([COUNT(DISTINCT CASE WHEN visit_type = 0 THEN visitor_id END)] + [COUNT(DISTINCT CASE WHEN visit_type = 0 THEN visitor_id END)]) AS Total You would think that there would be some gui functionality in VS08 that would do this... Thoughts are greatly appreciated! TT
View Replies !
Select Count(*)
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 Replies !
Select Count
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 Replies !
Select Count
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 Replies !
|