Transact SQL :: Sum Amount By Grouping Date
Oct 3, 2015
I have a table that have customer name and their bill amount
a) tblBilling
which shows records like below (Billing Dates are shown in Year-Month-Day format)
Invoice Customer BillingDate Amount Tax
--------------------------------------------------------------------------
1 ABC 20015-10-2 1000.00 500.00
2 DEF 20015-10-2 2000.00 1000.00
3 GHI 20015-10-2 1000.00 500.00
4 JKL 20015-10-3 5000.00 2500.00
5 MNO 20015-10-3 1500.00 750.00
6 PQR 20015-10-4 500.00 250.00
7 STU 20015-10-4 1000.00 500.00
8 VWX 20015-10-4 2500.00 1250.00
I want to perform a query that should SUM Amount and Tax Colums by date basis, so we could get the following result
BillingDate Amount Tax
--------------------------------------------------------------------------
20015-10-2 4000.00 2000.00
20015-10-3 6500.00 3250.00
20015-10-4 4000.00 2000.00
View 3 Replies
ADVERTISEMENT
Nov 18, 2015
I tried to ask a similar question yesterday and got shot down, so I'll try again in a different way. I have been looking online at the gaps and islands approach, and it seems to always be referencing a singular field, so i can't find anything which is clear to get my head around it.In the context of a hotel (people checking in and out) I would like to identify how long someone has been staying at the hotel (The Island?) regardless if they checked out and back in the following day.
Data example:
DECLARE @LengthOfStay TABLE
(
PersonVARCHAR(8) NOT NULL,
CheckInDATE NOT NULL,
CheckOutDATE NULL
[code]...
View 7 Replies
View Related
Oct 24, 2015
I want to frame a range of data based on particular group of columns
If OBJECT_ID('tempdb..#ResellerRange') IS NOT NULL
drop table #ResellerRange
create table #ResellerRange
( ResID varchar(10)
, amt decimal(18,2)
, serialno int)
insert into #ResellerRange ( ResID,amt, serialno )
values ('Raja',10,67),('raja',10,68),('raja',10,89),('Prabu',20,56)
I want below output
resid amt min max
----------------------------------
raja 10 67 68
raja 10 89 89
Prabu 20 56 56
View 5 Replies
View Related
Nov 19, 2015
I have typed a query by combining multiple tables to show sum of TotalReceivedAmount by MRN. It also have payment mode which is paid by cash or credit card. Now the query shows the sum for MRN combining all the payment done by credit card and cash. How am I supposed to show the amount paid by credit card and cash separately?
Here is the query :
SELECT Distinct dbo.CA_Payment.MRN, dbo.CA_Patient.FirstName, dbo.CA_PaymentModeMaster.Description AS PaymentMode,
CASE (dbo.CA_Payment.PaymentModeID) WHEN 2 THEN dbo.CA_Payment.CardNumber END AS CreditCardNumber, CASE (CA_Registration.PatientTypeID)
WHEN 1 THEN dbo.CA_PatientTypeMaster.Description WHEN 2 THEN dbo.CA_DebtorMaster.DebtorName END AS Debtor,
[Code ....
View 6 Replies
View Related
Aug 27, 2015
We have retention policy , and pay at the time year completion , now policy change and it is converted from yearly to monthly and this with effect from April-15.
if calculate the pay system will generate the Arrear payment of the employee from the month of April onward but i already paid the retention amount for month for two month April and May which i need to deduct the same otherwise this will double amount .
View 2 Replies
View Related
Apr 10, 2008
this is my sample records in my table
Sdate Amount
January 2007 250000.00
March 2007 300000.00
January 2008 350000.00
how can i get the amount from February to
May 2007 and sum it up like this
Details
February 2007 250000.00
March 2007 300000.00
April 2007 300000.00
May 2007 300000.00
this is all that i want to get
Total Amount: 1,150,000.00
i also posted this one in new to sql server section, but im hoping to get others opinion here. thnx
View 4 Replies
View Related
Nov 28, 2012
I have a sales tables which looks as below.
DEPARTMENT
Barnd_Name
Item_Group
S_DATE
S_AMOUNT
Administration
IBM
[code]....
Now i need Month Wise Running Totals.but i should check the following group as show below i that order
1) DEPARTMENT
1) Brand
3) Item Group
4) Month
View 12 Replies
View Related
Jan 17, 2007
I need to convert a date like 08/1/2009 to 0809
I also need to show currency as 100.00 and not 100.0000
How can I do these in a select statement?
SELECT CONVERT(Varchar(20),ExpirationDate,10) AS ExpirationDate, Amount FROM tblPayment
I appreciate any help!
View 5 Replies
View Related
Apr 23, 2015
I need to create an output from a T-SQL query that picks a numeric variable and uses the print function to output with leading zeroes if it is less than three characters long when converted to string. For example if the variable is 12 the output should be 012 and if the variable is 3 the output should be 003.
Presently the syntax I am using is PRINT STR(@CLUSTER,3) . But if @CLUSTER which is numeric is less than three characters I get spaces in front.
View 4 Replies
View Related
Jul 12, 2015
I was working on what I was told was SQL 2012 and it turns out it is SQL 2005. I wrote two procs that I need to convert to 2005. Here is the code:
SELECT
era_provider_name AS Provider,
RIGHT([era_upi], 5) AS 'ERA Upi',
[era_fy] AS 'ERA FY',
ProcGrp,
COUNT(DISTINCT UCI) AS 'Client Count',
[Code]....
I'm not finding an efficient way to do this. I cannot use GROUPING SETS with 2005. Here is the code for the second proc:
SELECT
CASE
WHEN GROUPING(era_provider_name) = 1 THEN 'TOTALS'
ELSE era_provider_name
END AS era_provider_name,
CASE WHEN GROUPING(era_fy) = 1 THEN 'TOTALFY'
[Code] ...
The results as in SQL 2012 are exactly as I would like them. I want to mimic those results in 2005.
View 6 Replies
View Related
Jul 8, 2015
I needed to add in the Fiscal Year (FY) to group my results by FY. I changed my code to the following:
/*
EXEC ADAMHsp_BSS_GetNonMedicaidReportTotals
@pstrProviderName = 'FAM SER-WOOD'
*/
ALTER PROCEDURE [dbo].[ADAMHsp_BSS_GetNonMedicaidReportTotals]
@pstrProviderNameVARCHAR(100)
AS
BEGIN
[Code] ....
See my result set in the picture below. The rows with NULL in the 'ProcGrp' column have the totals of the groupings by FY that I am looking for - that's great. What I want to do now is have another row that contains the sums of the values from any row where 'ProcGrp' is null so that I have a totals row.
View 3 Replies
View Related
Nov 4, 2015
I have a table as below
ItemID ParentID
6 NULL
7 NULL
8 7
11 7
12 8
Here ParentID null means it does not have the parent its the master. I want result in below format.
ItemID ParentID
6 NULL
--No parent no child
7 NULL
--No parent but has child
8 7
--7 is the parent of 8
12 8
--8 is the parent
11 7
--7 is the parent
Basically it should be in parent id then child id after that child's childID , In a recursive way.
View 5 Replies
View Related
Jul 9, 2015
I have a table with couple of hundred thousand records, i have added a new column to the table named MD_Group.
Now i need this column populated, so that every 10,000 row set in that table gets a numeric (incremental number) assigned starting from 1.
So the first 10,000 rows will have MD_Group = 1, next 10,000 rows will have MD_Group = 2 , next 10K MD_Group = 3 etc.
For testing purpose here is a results table with total of 11 rows where we want data grouped every 3 rows.
MD_Group
CustomerNumber
AmountBilled
1
12
15243
1
1231234
15243
[code]....
-- Create Sample Table
Declare @GroupRelation_Test TABLE (
MD_Group [varchar](20),
CustomerNumber [varchar](20) ,
AmountBilled [varchar](20) ,
[code]....
-- Test data
INSERT INTO @GroupRelation_Test
( CustomerNumber, AmountBilled,MinAmounttBilled)
SELECT'12','15243','' UNION ALL
SELECT'1231234','15243','' UNION ALL
SELECT'463','15243','' UNION ALL
SELECT'442','15243','' UNION ALL
[code]....
View 22 Replies
View Related
Jun 23, 2015
I have a table with duration values for different machine states. I 'm trying have a sum of the duration value of each state ( the duration sum , was an earlier question).
declare
@tblDurations
TABLE
(StateName
nvarchar(30),Duration
nvarchar(30))
[code]...
I want the output to have sum of the duration ( from my function ), grouped by the state.So output should be :
Breaks 00:02:03:40
Meetings 00:00:01:50
Running 15:21:07:16
I think this can be done with windows functions, but how I don't know.
View 10 Replies
View Related
Nov 6, 2015
I have two tbles that have ItemName and their bill amount
a) tblLunch
which shows records like below
Invoice Item Amount
--------------------------------------------
1 COFFEE 1000.00
2 TEA 2000.00
3 ICE CREAM 1000.00
b) tblDinner
which shows records like below
Invoice Item Amount
------------------------------------------------------------
1 COFFEE 1000.00
2 TEA 2000.00
3 PASTA 1000.00
I want to perform a query that should SUM Amount Columns by Grouping the Item from both the tables, so we could get the following result
Item Amount
------------------------------
COFFEE 2000.00
TEA 4000.00
ICE CREAM 1000.00
PASTA 1000.00
View 3 Replies
View Related
Aug 9, 2015
In the below query, I can get the individual/single group by columns as well as multiple but I cannot control the order in which I would like to group by the data.
So lets say I want to group the data by OS->browser->browser_version(just one example) then I cannot achieve that as the order of OS column comes later in the query.
I know one option would be to write a dynamic SQL but i dont want to do that because of performance reasons. Any other way this can be achieved?
select
case when @include_browser =
1 then browser_name end as browser_name,
case when @include_browser_version
= 1 then browser_version end
as browser_version,
[Code] ....
View 4 Replies
View Related
Dec 5, 2015
I have a table like this.
AS-IS
Column1 Column2 count
a b 20
a b 25
c d 12
c d 22
And I need to update the same as below.
TO-BE
Column1 Column2 count
a b 45
c d 34
How to do it?
View 4 Replies
View Related
Jul 29, 2015
I am trying to generate XML path from a SQL Server Table. Table Structure and sample data as below
CREATE TABLE #OfferTransaction
( [OfferLoanAmount1] INT
,[offferid1ProgramName] VARCHAR(100)
,[Offer1LenderName] VARCHAR(100)
,[offerid1LenderNMLSID] INT
[code]....
what changes do I need in my query so that the XML looks like the one above ( DESIRED XML). Is it possible via query changes?
View 3 Replies
View Related
Nov 5, 2015
Below is the data I have in table name
TeamStatus
T 1 Complete or Escalate
T 2 Pick Up
T 2 Resolve Case
T 1 Pick Up
T 1 Complete or Escalate
T 1 Pick Up
T 1 Complete or Escalate
I want to get he group based of Resolve Case value in Status Column. Anything before Resolve case will be considered as Group 1 and after Resolve Case status should be considered as Group 2. Below is desired new Group column,
Group TeamStatus
Group 1 T 1Complete or Escalate
T 2 Pick Up
T 2 Resolve Case
Group 2 T 1Pick Up
T 1Complete or Escalate
T 1 Pick Up
T 1 Complete or Escalate
View 7 Replies
View Related
Sep 23, 2015
I've unpivoted some data and stored it in a temp table variable
idNumFreqDtFreqrn
16100120120101M2
16100120120101M3
16100120100101M4
16100120100101M5
16100120060101M6
16100120000929Q7
16100119990101A8
16100119970101M9
Using the above data, if two rows have the same FreqDt, I want to see the record with the lowest row number.
So it should look like the below
idNumFreqDtFreqrn
16100120120101M2
16100120100101M4
16100120060101M6
16100120000929Q7
16100119990101A8
16100119970101M9
I've used the below code to accomplish it
SELECT DISTINCT
CASE WHEN t2.idNum IS NULL THEN t1.idNum ELSE t2.idNum END,
CASE WHEN t2.FreqDt IS NULL THEN T1.FreqDt else t2.FreqDt END,
CASE WHEN t2.freq is null then t1.freq else t2.freq end
FROM @tmptbl as t1 LEFT JOIN @tmptbl as t2
ON t1.idNum = T2.idNum
AND t1.FreqDt = t2.FreqDt
AND t1.rn = (t2.rn-1)
After all this, I'm supposed to condense the result set to only include sequential frequency dates with unique frequencies.should look like below (this is where I'm stuck)
idNumFreqDtFreq
16100120060101M
16100120000929Q
16100119990101A
16100119970101M
answer is below:
SELECT T1.*
FROM @t as t1 LEFT JOIN @t as t2
ON t1.idnum = T2.idnum
AND t1.freq = t2.freq
AND t1.rn = (t2.rn-1)
WHERE t2.idnum IS NULL
View 5 Replies
View Related
Jun 15, 2015
How do you incorporate a case statement so that you can add "sub total" and grand total" to each grouping set section? Trying to see how to incorporate case.
[URL] ....
SELECT
CustomerID,
SalesPersonID,
YEAR(OrderDate) AS 'OrderYear',
SUM(TotalDue) AS 'TotalDue'
FROM Sales.SalesOrderHeader
[Code] .....
View 4 Replies
View Related
Jan 3, 2007
Hello All,
Noob here. Trying to group by date in report and it is not working as expected. The date fields include a date/times i.e. 12/23/2006 9:45:00 AM. I can change the date properties to make the data appear as 12/23/2006, but when I group on date, it returns multiple rows showing the same date instead of just one row with the one date. The data is aggregated for the grouping so it seems like it should work properly. Here is an example of what I am trying to do.
Current...
Date Data
12/23/2006 9:45:00 AM 12
12/23/2006 10:00:00 AM 8
12/23/2006 10:15:00 AM 5
Want it to be...
Date Data
12/23/2006 25
Using SQL Server 2000 and RS2000
Thanks,
Clint
View 5 Replies
View Related
Nov 9, 2015
I have two tables Costtable (Id,ResourceId, Amount,Date) and ResourceTable (ResourceId,Name) which shows output as below.
I want to show 0 amount for rest of the name in case of September. For e.g. if rest of the Resources does not appear in cost table they should appear 0 in amount
My Desired output
My current query
SELECT
RG.Id AS Id,
RG.Name AS Name,
ISNULL(SUM(AC.Amount), 0) AS Amount,
RIGHT(CONVERT(varchar(10), AC.[Date], 105), 7) AS [YearMonth]
[Code] ....
View 6 Replies
View Related
Mar 2, 2001
I store data in a table using a column named InsertTimestamp which is a datetime format. I now want to report on rows by just the date. I have been able to do this by converting the datetime like such:
convert(varchar, inserttimestamp, 107)
This reurns the data correctly however is very ineffiecnet. DOes anyone know another easy way around this dilemna???
View 1 Replies
View Related
May 12, 2006
I'm using SQL Server 2000.
Example table:
PeopleID Date Status
1 2004-01-01 True
1 2005-01-01 True
1 2006-01-01 True
2 2004-01-01 True
2 2005-01-01 False
2 2006-01-01 True
I'm trying to find a way to query whether or not someone has had a specific status for 3 years in a row. As you can see from the table above, PeopleID 1 has had a "Status" of "True" for 3 years in a row, whereas PeopleID 2 hasn't--there was one year where they had "False".
I'm wondering I can query this, or if I'm going to have to scan the records manually. :(
I suppose I could write a stored procedure and do some looping too.
Appreciate any help, thanks!
View 2 Replies
View Related
May 7, 2008
Hi I am having trouble and I don't know why.
I have this query which I pasted below. I need to find the earlist effective date (pcsp_eff), but I need to show all of the fields below in my report like a flat file. I know ususaly when you use Max/Min you have to have a group by, would I group by everything that is in my select statement?
SELECT Distinct
dbo.pcs.pcs_id1,
dbo.pcs.pcs_lname AS [Last Name],
dbo.pcs.pcs_fname AS [First Name],
dbo.pcsp.pcsp_eff AS [Effective Date for Provider],
Min(pcsp_eff) as "earliestEffectivedate",
dbo.pcst.pcst_trm1 AS [Tracking Thru Date],
dbo.pcst.pcst_dat3 AS [Re-cred Letter Sent Date],
dbo.pcst.pcst_dat7 AS [Re-cred Complete Date],
PRO_STATE as "State",
PRO_COUNTY as "County"--, PCSP_NET
FROM dbo.pcs INNER JOIN
dbo.pcst ON dbo.pcs.pcs_id1 = dbo.pcst.pcst_id1 INNER JOIN
pcsp ON pcs.pcs_id1 = pcsp.pcsp_id1 left Join
dbo.pro ON pcs.pcs_id1 = pro.pro_id1
WHERE
(CONVERT(CHAR(10), dbo.pcst.pcst_dat3, 110) <>'03-23-1977') and
(CONVERT(CHAR(10), dbo.pcst.pcst_dat7, 110) = '03-23-1977') and
(pcsp.pcsp_prd = 'DGH') AND
--(pcsp.pcsp_id2 = '0001') and
PCS_CTL = 'I' and
pcsp_NET <> 'DACFP' and
pcs_id1 = '00004307'
Group by pcs_id1
View 2 Replies
View Related
Mar 14, 2008
My company is unusual in that our accounting periods are not actual months. We have what we call "Red Fridays." These are spaced 3-5 weeks apart. So, my company doesn't care what happened in the month of April, but they care what happened between April 4 and May 2 because these are the Red Fridays.
So, I have created a database with a table called "RedFridays" with the dates for this year. I want to combine this with various tables in our ERP database. I use a Left Outer Join between the Red Friday Dates and the corresponding date in the ERP database.
I need to create a custom grouping formula which accomplishes the following:
1. Subtract a certain number of months from today's date to determine which Red Friday would be the correct starting date.
2. Group records by date between that Red Friday and the second one. This would be listed as something like "Month 1".
3. Continue grouping in this way to the present date and that Red Friday range.
Can anyone point me in the right direction? Any help would be greatly appreciated.
View 5 Replies
View Related
Mar 19, 2008
Here's my sql which works
SELECT tblFileRequests.Dept, tblFileRequests.Division, tblFileRequests.Sect, COUNT(*) AS Expr1
FROM tblFileRequests LEFT OUTER JOIN
tblFileRequestDetails ON tblFileRequests.MovementId = tblFileRequestDetails.MovementId
GROUP BY tblFileRequests.Division, tblFileRequests.Sect, tblFileRequests.Dept
ORDER BY tblFileRequests.Dept, tblFileRequests.Division, tblFileRequests.Sect
I also want to include tblFileRequestDetails.DateOut but this cause my grouping to go haywire. How can I include it ? Ultimately I want to create a stored procedure and crystal report based on it. Thanks
View 20 Replies
View Related
Apr 5, 2007
Hello,
I have the following problem.
I a making reports based on a database that i do not control.
In that database i have a table with statistical data including a field with datetime informtion.
The format of the data I receive is "5/04/2007 7:43:27".
In my report i want to create a group which groups my event by date : "05/04/2007"
In my output i always get subgroups by date & time so "5/04/2007 7:43:27", "5/04/2007 7:43:28", ....
How can i group only on the date.
Vincent
View 13 Replies
View Related
Jan 17, 2002
I'm adding up quantities of an item that are entered in one after another, so the date is the same, but the time differs.
I used the "first" function in access which works the way I want, but sql7 doesn't use the same function. The "convert" function does not work in access but Here is the gist of the query:
SELECT first(CONVERT(varchar,transactions.tran_date,101)) AS [trandate], transactions.tran_type,
SUM(transactions.qty) AS totqty,...etc.
thanx,
Herb
View 1 Replies
View Related
Mar 18, 2008
I'm creating a temporary table in a Sql 2005 stored procedure that contains the transaction amount entered in a period <= the period the user enters.
I can return that amount in my result set. But I also need to separate out by account the amounts just in the period = the period the user enters. There can be many entries or no entries in any period. I populate the temporary table this way:
SELECT
t.gl7accountsid,
a.accountnumber,
a.description,
a.category,
t.POSTDATE,
t.poststatus,
t.TRANSACTIONTYPE,
t.AMOUNT,
case
when t.transactiontype=2 then amount * (-1)
else amount
end as transamount,
t.ENCUMBRANCESTATUS,
t.gl7fiscalperiodsid
FROM
UrsinusCollege.dbo.gl7accounts a
join
ursinuscollege.dbo.gl7transactions t on
a.gl7accountsid=t.gl7accountsid
where
(t.gl7fiscalperiodsid >= 97
And
t.gl7fiscalperiodsid<=@FiscalPeriod_identifier)
And poststatus in (2,3)
and left(a.accountnumber,5) between '2-110' and '2-999'
And right(a.accountnumber,4) > 7149
And not(right(a.accountnumber,4)) in ('7171','7897')
order by a.accountnumber
Later I create a temporary table that contains budget information. I join these 2 temporary tables to produce my result set. But I don't know how to get the information for just one period. For example, if the user enters 99 as the FiscalPeriod_identifier, I need a separate field that contains only those amounts(if any) that were entered for each account in Period 99.
Can anyone help? It may be that I am not seeing the forest for the trees, but I can't figure it out.
Thanks very much.
Sue
View 6 Replies
View Related
Jul 13, 2000
Hi,
I have a requirement to be able to select and group records by the date portion of a datetime field. ie ignore the time when grouping so that all records lodged on a particular day are seen together.
I have been able to do this by
- converting the datetime data to the number of days since a given date
- inserting this into a temporary table
- retrieving the the data from the temporary table
- convert the data back to a date using DATEPART to display dd/mm/yy
This then gives me the data grouped as required but seems to be a very difficult solution - Is there an easier way??
Thanks in advance
jan
View 3 Replies
View Related
Aug 2, 2004
Masters,
The below queries return the data that I seek, but I have no idea how to combine them into a single query.
SELECT SUM(TOTALSVCAMT) - SUM(TOTALPAYMENTAMT) - SUM(TOTALADJAMT) as [0 to 30]
FROM MDM2
WHERE DATEDIFF(day, SERVICEDATE, getdate()) between '0' and '30'
SELECT SUM(TOTALSVCAMT) - SUM(TOTALPAYMENTAMT) - SUM(TOTALADJAMT) as [31 to 60]
FROM MDM2
WHERE DATEDIFF(day, SERVICEDATE, getdate()) between '31' and '60'
SELECT SUM(TOTALSVCAMT) - SUM(TOTALPAYMENTAMT) - SUM(TOTALADJAMT) as [61 to 90]
FROM MDM2
WHERE DATEDIFF(day, SERVICEDATE, getdate()) between '61' and '90'
SELECT SUM(TOTALSVCAMT) - SUM(TOTALPAYMENTAMT) - SUM(TOTALADJAMT) as [90+]
FROM MDM2
WHERE DATEDIFF(day, SERVICEDATE, getdate()) > '90'
Any assistance that can be provided will be greatly appreciated.
Grasshopper
View 1 Replies
View Related