Transact SQL :: Single Records - Loop To Only Insert Sum Total Of Each Day
Apr 22, 2015
I have the following query:
BEGIN TRAN
Declare @StartDt date = '2015-03-15'
Declare @EndDt date = DATEADD(M, 1, @StartDt)
declare @Days int = DATEDIFF(d, @StartDt, @EndDt)
declare @TBLSales as table(SaleDate date, Value money)
DECLARE @Today date
declare @TBLSalesCounts as table( StatusDesc varchar(100), Value money)
[Code] ....
I end up with the following result :
How would I alter my while loop to only insert the sum total of each day, instead of creating duplicates for each day.
E.g.
2015-04-22
1150.00
2015-04-21
785.00
2015-04-20
750.00
If I just use a simple select statement, I find that I have 8286 records within a specified date range.
If I use the select statement to pull records that were created from 5pm and later and then add it to another select statement with records created before 5pm, I get a different count: 7521 + 756 = 8277
Is there something I am doing incorrectly in the following sql?
DECLARE @startdate date = '03-06-2015' DECLARE @enddate date = '10-31-2015' DECLARE @afterTime time = '17:00' SELECT General_Count = (SELECT COUNT(*) as General FROM Unidata.CrumsTicket ct
I'm trying to pull all records from one table and just a single record from another. I have this join, (see below). It works ok, but the problem is if a blog record doesn't have a corresponding image record it doesn't return. The end result should be the blog record and a single corresponding image record. But always a blog record.
Is there a way to insert multiple records into a database table when you're just given "count" of the number of rows you want? I want to do this in ONE insert statment, so I don't want a solution that loops round doing 100 inserts - that would be too inefficient.
For example, suppose I want to create 100 card records starting it card number '1234000012340000'. Something like this ...
declare @card_start dec(16) set @card_start = '1234000012340000' declare @card_count int set @card_count = 100
1.First i need to update the row if the status column is 0 to 1 2.Need to insert the row IF SegmentId=@SegmentId and SubjectId<>@SubjectId and StaffId=@StaffId 3.Need to insert the row IF StaffId<>@StaffId And ClassId=@ClassId and SegmentId<>@SegmentId and SubjectId<>@SubjectId
I have wrote the stored procedure to do this, But the problem is If do the update, It is reflecting in the database by changing 0 to 1. But it shows error like cannot insert the duplicate
Lets say we are executing this query below to retrieve each customer and the amount associated to a table
"INSERT INTO tblReceiptDue (Dealer, Amount) SELECT CustomerName, SUM(CASE WHEN VoucherType = 'Sales' then Outbound ELSE - Inbound END) AS AMOUNT from tblSaleStatementCustomer WHERE CustomerType = 'Dealer' GROUP BY CustomerName"
I'm trying to insert records into "holding" table and write back identity column value (Entry_Key) to the original table. So my setup is I have two tables; tblEWPBulk and tbleFormsUploadEWP. Users will enter records into tblEWPBulk and use BatchID to group records, once batch entry has been completed (usually less than 30 records) user will click on UploadAll button and insert records (not all fields) into tbleFormsUploadEWP. One record in tblEWPBulk can be sent multiple times to the holding table but tblEWPBulk will need to have latest Entry_Key captured. Records are sent from holding table to DB2 z/VSE using SQL stored procedure and based on certain logic records are marked uploaded or certain error capture... that part works fine.
So for example I want to send
BatchID, AccountNumber, Period, ReceiveDate, AccountType, ReturnType, NetProfitOrLoss, TaxCredit FROM tblEWPBulk to the holding table and write back Entry_Key (identity column) back to the record in tblEWPBulk (field called UploadEntryKey). As I said one record could be sent to the holding table multiple times until uploaded or deleted and UploadEntryKey always needs to be updated so that when results are processed response from the DB2 can be inserted into table and presented to the user.
No foreign key relationship exists since records in the holding table get sent to the archive table and table is truncated and entry_key starting value reset back to 2000... just some DB2 restrictions.
Can we push the data for the above query in a physical table and create index to make the query fast rather than using the same set tables multiple times
writing the query for the following, I need to collapse the continuity. If the termdate for an ID is one day less than the effdate of the next id (for the same ID) i need to collapse the records. See below example .....how should i write the query which will give me the desired output. i.e., get min(effdate) and max(termdate) if termdate is one day less than the effdate of next record.
I am trying to create a procedure which will calculate the total tuition This process involves 3 tables. Contract table has tuition information which is all $100 (set price). Discount table has discount type and discount percentage (ex. 0.3) on each discount type. ContractDiscount table have contract number and discount number to connect both tables
I think I need to create a loop since some contract gets more than one discount. I have to calculate and get result nee to be like this
total_tuition = (tuition - discountPer * tuition) - this has to be a loop condition
I want to return the total number of rows and top n records from my query. Is it possible to do this by simply running a single query. My query is dynamic so I can not create any temp table or table variables.
Bacially I want to eliminate 2 calls for sp_executesql
Set @ColumnCount = "Count(*)" Set @Columns = " Top 100 a,b,c" Set @Filter = "a = 1001"
Set @sql = "select " + @ColumnCount + " FROM TABLEA WHERE " + @Filter sp_executesql @Sql
Set @sql = "select " + @Columns + " FROM TABLEA WHERE " + @Filter sp_executesql @Sql
I was writing a query to get the age and the retirement year for all the employees.And thought of using while loop so that I don't have to write IF conditions or case statements for all the ages.
I'm using the AdventureWorks2012 database.And the actual table looks like this.
SELECT * FROM HumanResources.Employee
*NOTE:- These tables are not the complete tables.
BusinessEntityID JobTitle BirthDate MaritalStatus Gender 1 Chief Executive Officer 1963-03-02 S M 2 Vice President of Engineering 1965-09-01 S F 3 Engineering Manager 1968-12-13 M M 4 Senior Tool Designer 1969-01-23 S M
[Code] ...
And after I wrote the query to get the age and the retirement year of all the employees I got 70 tables for all the ages from 30 to 70. As the starting age is 30 and the last age is 70 in the table.So,I just want to know how I can settle all the tables into a single table as a sinle result and not as multiple results.
The query for age and retirement year....
DECLARE @Counter INT DECLARE @Duration INT DECLARE @Result DATE SET @Counter=(SELECT MIN(DATEDIFF(YY,BirthDate,GETDATE()))FROM HumanResources.Employee) SET @Duration=30
[Code] .....
And the result tables.
BusinessEntityID JobTitle BirthDate AGE MaritalStatus Gender Retirement Year69 Production Technician - WC60 1985-05-07 30 S M 2045-08-25 22:36:38.160115 Production Technician - WC50 1985-07-01 30 S F 2045-08-25 22:36:38.160133 Production Technician - WC40 1985-02-04 30 S M 2045-08-25 22:36:38.160144
[Code] ....
And it goes like this for 70 times. So just want to know how I can merge those 70 tables into a single table.
tblPayments (Contains the records of Payments we made)
ID DATE AMOUNT BANK ---------------------------------------------------------- 1 05/05/2015 5000 Natwest 2 05/05/2015 2000 Lloyds 3 05/06/2015 3500 Natwest 4 05/07/2015 4000 Natwest 5 05/08/2015 1500 Lloyds
tblReceipts (Contains the records of Receipts we received)
ID DATE AMOUNT BANK ---------------------------------------------------------- 1 05/06/2015 5000 Natwest 2 05/06/2015 2000 Lloyds 3 05/07/2015 3500 Natwest 4 05/07/2015 4000 Natwest 5 05/08/2015 1500 Lloyds
Now, I also have a blank table (tblBankStatement) which contain the following columns
ID DATE RECEIPT PAYMENT BANK -----------------------------------------------------------------------------
I want that when I execute the query, the query should INSERT the records to the New Table (tblBankStatement) from tblPayments and tblReceipts by Date Ordered in ascending way WHEREBank should be 'Natwest'.
Also the Amount Column Data in tblPayments should be Inserted into the Payment Column in tblBankStatement and the Amount Column Data in tblReceipts should be Inserted into the Receipt Column in tblBankStatement.
I have a SQL data source and i would like to present the total number of different records based on a "status" field. I have done total records in the past by doing this: protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e) { int RecordCount = e.AffectedRows; if (RecordCount == 1) { litRecordCount.Text = "1 record found"; } else { litRecordCount.Text = RecordCount.ToString() + " records found"; } } This would work, howerver, my SQLdatasource choose * records, and not based on a WHERE condition. Is there any way to total just those with a status of "Initialized" ? I tried to do it on the Gridview, but then I realized if I have paging on, it will only be on that front page. thoughts?
I am creating a query that shows the consumption of stock against Manf Orders (M/O) and struggling on the last hurdle. I am having difficulties calculating a running total based on an Opening Balance. The first line returns the correct results but the following lines do not. I have tried other variants of the "Over Partition" but still no joy?
SELECT CASE WHEN ROWNUMBER > 1 THEN '' ELSE A.Component END AS Component , CASE WHEN ROWNUMBER > 1 THEN '' ELSE A.SKU
Hello, I am having problems with this query below: 1 SELECT Table1.Email AS Email, 2 Table2.UserName AS Username, 3 Table3.Members_Paid AS Paid, 4 (SELECT DISTINCT COUNT(*) 5 FROM Table3 AS e JOIN Table3 AS m 6 ON e.Members_Sponsor = m.Members_ID 7 WHERE (e.Members_Sponsor = m.Members_ID)) AS TotalRecords 8 FROM Table1 INNER JOIN 9 Table2 ON Table1.UserId = Table2.UserId INNER JOIN 10 Table3 ON Table2.UserId = Table3.UserID 11 WHERE (Table3.Members_Sponsor = @UserId)Basicly what I am trying to do is get all members that belong to a certain manager along with those members count total of members they have below them.The code above is giving me the count of the first member only, not different counts for each member.Hope you understand what I am trying to say and do here. Hope someone can help me out cause this hase been driving me crazy for a few days now.
I want find out Total number records in one table without using select statment. Some body as told to me there is system table you can find total number of records. Any body give me systable name. Thanks Jack
I want find out Total number records in one table without using select statment. Some body as told to me there is system table you can find total number of records. Any body give me systable name. Thanks Jack
I tried my syntax below, but it said that the field were not in the group by. This is syntax and for each of the 2 names (only small subset of real data) I need a Total column to display between each different person like so:
I have a table like below, which is contain area, zone, branch wise value. In that i want to get company total as a column and area total as a another column and zone total in next column
I achieved this by using query but its will affect performance because my real time scenario dealing with laks of records
select a.*,b.company_tot,c.area_tot,d.zone_tot from FESIBILITY_CHECK a cross join (select SUM(value)company_tot from FESIBILITY_CHECK )b join (select SUM(value)area_tot,area from FESIBILITY_CHECK group by area)c on a.AREA = c.area join (select SUM(value)zone_tot,area,zone from FESIBILITY_CHECK group by area,zone)d on a.AREA=d.area and a.ZONE = d.ZONE
So I planned to use cube and roll up but i don't get desired result ...
My query below displays a total row, but it displays above the city, I want it to display below the city. But now their is an additional caveat, I have a table that sets the order each city & total row should display in. How can that be added to my query to set the display order?This is what I have that displays the total above the city, could this be ammended to join in the order table and display in that order? SQL Server 2008
WITH OrderedResults AS (SELECT some_table.*, ROW_NUMBER() OVER (ORDER BY some_field) as RowNumber FROM some_table) SELECT TOP 10 * FROM OrderedResults WHERE RowNumber > 10;
which works well for returning "paginated" recordsets. But when it comes to displaying "page" links and next and previous links, I need a total count of records found... something along the lines of the MySQL CALC_FOUND_ROWS feature...
Is there some built-in MSSQL feature I can use for this, or do I have to do a SELECT count(*) FROM some_table to get this data?
SELECT vehicleref, capID, make, model, derivative, COUNT(vehicleref) total, SUM(case when inStock=1 then 1 else 0 end) AS stock, (SELECT dealer FROM tblMatrixDealers WHERE id=dealerid) As Dealer FROM tblMatrixStock WHERE inStock = 1 GROUP BY vehicleref, capID, make, model, derivative, dealerid
I need to get the number in stock, i.e. when instock=1 and the total i.e. when instock=1 or 0
But the problem is i'm only showing records where instock=1 so my SUM(case when inStock=1 then 1 else 0 end) AS stock statement is useless.
I need to get a cumulative total for row by row basis. I need this grouped on name, id, year and month. ID is not a auto incremented number. ID is a unique number same as name. The out put I need is as below,
Name ID Year Month Value RunningValue XX 11 2013 Jan 25 25 xx 11 2013 Feb 50 75 yy 22 2015 Jan 100 100 yy 22 2015 Mar 200 300
How I could get this query written? I am unable to use SQL Server 2012 version syntaxes. Writing a cursor would slow the process down because there is a large data set.
How can I add a Total Column as the last column in this query and also add a total column to the bottom row of the query? Then after the total column on the right, add a % column. So my expected returned set would be like so:
Hi guysI'm mulling over the best way to do something and would like your input. Forgive me if this is a bit 101 - I haven't ever had to do this in SQL before!Fairly standard set up - Hierarchy table modelling the structure of an organisation.Related table associating members of staff to the hierarchy.I want to return all levels of the hierarchy and for each level I would like to know the total number of people in the level (so for a division it would be the sum of all people in the child teams).Parameters - This table will be modelling many organisations' structures - I cannot guarentee anything like "there will never be more than n levels". As such - I would strongly prefer to have something that is iterative recursive. I can change the schema to suit the method I use if necessary. Database is not transactional - I am not concerned about updating speed. SQL Server 2K5.I've tried CTE but it turns out you cannot use group by in CTEs (even in derived tables). I have not yet tried feeding it a view or similar.I have not tried nested sets, materialised paths, accumulator table - I thought I would see if there is something obvious before I start piddling around with those.Ta!