SQL 2012 :: Calculate Stock Aging Based On Hand Quantity

Jan 18, 2015

I want to calculate stock aging (qty, cost) based on the on hand quantity.

Currently I am recording only in/out transaction only.

For ex: Item A i have 115 pieces (Balance stock) as on to day.

Transaction History
---------------------
Lot 1 - 01/01/2015 - 50
Lot 2 - 10/02/2015 - 50
Lot 3 - 11/03/2015 - 50
Lot 4 - 15/04/2014 - 50

I want to calculate cost of balance qty as shown below.

Jan -
Feb - 15 @ 1.1
Mar - 50 @ 0.90
Apr - 50 @ 1.2

Database schema
--------------------
CREATE TABLE [dbo].[StockManagement](
[Uniid] [int] IDENTITY(1,1) NOT NULL,
[StockCode] [int] NULL,
[TransactionDate] [datetime] NULL,
[TransactionTime] [time](0) NULL,

[Code] .....

View 0 Replies


ADVERTISEMENT

Make Procedure For Stock-quantity

Sep 3, 2007

 helo alll...,this is my data:my table is item(productid,stock) ,order(customerid,no_order), and orderdetail (no_order,productid,quantity) example: order and orderdetail displayed in gridview....order is displayed like this:                 customerid            no_orderdetail                  A                        1detail                  B                        2  when i click detail in row 2, it's display orderdetail:no_order               productid              quantity       2                            c1                       2  2                            p1                       3 i have make all this is ok. but i want to decrease stok in item with quantity in orderdetail.my code in procedure like:CREATE PROCEDURE [dbo].[order_item](@productid AS varchar,@quantity AS INT)ASBEGINBEGIN TRANSACTIONDECLARE @no_order AS INTDECLARE @stock AS INTINSERT INTO [Orderdetail]([ProductId],[Quantity])VALUES(@productId,@quantity)SET @no_order = SCOPE_IDENTITY()SET @Stock = (SELECT [Stock] FROM [item] WHERE [ProductId] = @productId)UPDATE [item]SET[Stock] = @Stock - @quantityWHERE[ProductId] = @productIdCOMMIT TRANSACTIONENDreturn it can't work..how about his true code in store procedure?ok..., thx.. 

View 8 Replies View Related

Identify Genuine Stock Quantity Discrepancies Between ERP And WMS?

Dec 11, 2014

I have been asked to report on missing Stock in my works Warehouses. My work uses SAP Business One for ERP, and Accellos for Warehouse Management. Both SAP / Accellos maintain stock levels, and whilst they do talk to each other (in real time), nothing is perfect and stock counts (within each system) sometimes develop discrepancies.

Here is the code that I developed to show stock discrepancies -

Code:
SELECT
Tx.[Item Code]
, ISNULL(Ty.Qty, 0) AS 'A1 Qty'

[Code]....

View 1 Replies View Related

Transact SQL :: Create Query For Last Stock Quantity?

Sep 10, 2014

I need to create query for last stock quantity.

I have 3 tables. Stores, Dates and Transactions. I want to combine all Stores with all Dates in one table and then calculate Last Stock Quantity.

Stores
London
Paris
Prague

Dates
1.1.2014
2.1.2014
3.1.2014

Transactions
1.1.2014 London 1000
1.1.2014 Paris 1300
1.1.2014 Prague 1500
2.1.2014 London 800
3.1.2014 Prague 1200

And result should look like this Last_Quantity should be Quantity for last date in Transactions table.

1.1.2014 London 1000
1.1.2014 Paris 1300
1.1.2014 Prague 1500
2.1.2014 London 800
2.1.2014 Paris 1300
2.1.2014 Prague 1500
3.1.2014 London 800
3.1.2014 Paris 1300
3.1.2014 Prague 1200

View 8 Replies View Related

Shopping Cart, How Do I Subtract The Quantity Purchased From The Stock In Database?

Dec 11, 2007

Im making a shopping cart website for a school project in ASP.net with VB. I need help subtracting the quantity purchased (its saved in a session) from the stock number saved in a database.I know this:UPDATE inventory SET stock = stock - <quantity_purchased> WHERE id = <inventory_id>But I dont understand how to get the quantity purchased from the session to <quantity_purchased>. I tried putting the name of the session there and I got an error, i tried saving the session into a dim didnt work either.
 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [stock] FROM [product]" InsertCommand="INSERT INTO [product] ([stock]) VALUES (@stock)" UpdateCommand="UPDATE product SET stock = (stock - @Quantity) WHERE (productID = @productID)">
<InsertParameters>
<asp:Parameter Name="stock" Type="Int16" />
</InsertParameters>
<UpdateParameters>
<asp:SessionParameter Name="Quantity" SessionField="Quantity" Type="Int32" />
<asp:SessionParameter Name="productID" SessionField="productID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
 and I have than in my VB code on submit : SqlDataSource1.Update()

View 1 Replies View Related

SQL Server 2012 :: List Of Order Numbers Based On Stock Availability - Filter Results?

Dec 23, 2014

Trying to build a list of order numbers based on stock availability.

The data looks something like this:

OrderNumber Stockcode quantityordered quantityinstock
123 code1 10 5
123 code2 5 10
124 code3 15 20
124 code4 10 10

In this case I would like to output a single result for each order, but based on stock availability order 123 is not a complete order and 124 is so the results will need to reflect this.

View 1 Replies View Related

Transact SQL :: How To Calculate A Running Stock Value

Oct 8, 2015

I have the following store procedure :

SELECT APHIST.ReturnDate AS ATDATE
,API_HIST.[ActionPlanItemID]
,API_HIST.[ActionPlanID]
,PIT.[ProductItemID]
,PIT.ProductItemCode
,PIT.Name,

[code]....

What I am trying to get is a RunningStock level column which is able to display stock level as describe below :

If ItemStatus value is 0, that means that the item has been taken out from stock.

So based on that the first row running Stock level is calclulated as

(ProductQuantity * ItemUnitWeight)-ItemQuantity=9...

For the second record, ItemsStatus=1 which means the item return to stock, at the time the running stock value calculation should be the previous row Running Stok value (=9 ) +(ItemQuantity*ItemUnitWeight)When the ItemStatus=2, that means the item is definitely out and will be never back to current stock. Is there a way to get that calculation field ?

View 6 Replies View Related

Calculate A Range Bar From (stock) Tick Prices?

Dec 30, 2011

Assume you have a table called Tick with 2 columns
(
tickId bigint IDENTITY(1,1)
, price int -- usually money data type, making it int for simplicity
)

I am tasked with creating bars that are 10 units long.

Now the catch is I'm not looking for the tickId where price is >= t1(price) + 10 where t1(price) is the price for the first row where tickId = 1. (it could also be where price <= t1(price) - 10)

Here is sample data:

1, 25
2, 26
3, 23
4, 26
5, 27
6, 30
7, 34
8, 32
9, 30
10, 33

What I am looking for are rows 3 (23) and 7 (34)

Currently I have:

Code:
DECLARE @tickDiff int
SET @tickDiff = 10
DECLARE @r1TickId bigint

[Code].....

This seems to work but it is taking multiple minutes to run for about 50k rows of data (which I created off of the 24 million row table I have just looking at data from today). So it takes ~5 minutes to create the first bar which is not acceptible.

If my logic above seems acceptable are there any indexes you could recommend. Database engine tuning advisor didn't find any.

View 2 Replies View Related

On Insert Need To Calculate A Quantity

Jan 31, 2008

In my Insert into #TempTable I need to calculate the 'qty_wasted' as difference between 'qty_received' and 'qty_used' Where would I put the calc statement?


CREATE TABLE#TempTable
(
job_date datetime,
job_number char(15),
cost_code char(15),
qty_received decimal(8,2),
qty_used decimal(8,2),
qty_wasted decimal(8,2),
productId char(25),
plant_id char(10)
)


INSERT INTO #TempTable (job_date, job_number, cost_code, qty_received, qty_used, qty_wasted, productId, plant_id)
SELECT dbo.Batch.ReportDate AS job_date, dbo.Job.CompanyJobId AS job_number, dbo.Item.CompanyItemId AS cost_code, dbo.Product.CompanyProductId as productId, SUBSTRING(dbo.Job.CompanyJobId, 1,3) as plant_id,
qty_received = CASE dbo.SourceType.CompanySourceTypeId WHEN 'MA' then SUM(dbo.ProductionEvent.Quantity) ELSE 0 END,
qty_used = CASE dbo.SourceType.CompanySourceTypeId WHEN 'PR' THEN SUM(dbo.ProductionEvent.AlternateQuantity) ELSE 0 END
FROM dbo.Batch INNER JOIN
dbo.Event ON dbo.Batch.BatchGuid = dbo.Event.BatchGuid INNER JOIN.....

View 1 Replies View Related

Calculate Price For Quantity

Feb 20, 2008



Hello all, I have an interesting question about calculating a price in my database for a quantity entered. I have a join table that I store ProductID, SizeID, Quantity and Price. The price for a particular product changes based most often on the quantity ordered. For example, if you order one unit of a widget the price is 10.00, however if you order one dozen units of the same widget the price drop to 9.75 and so on.

Here is a sample of my table....columns are in the order I specified above.

1, 1, 1, 10.00
1, 2, 1, 10.00
1, 3, 1, 10.00
1, 1, 6, 9.90
1, 2, 6, 9.90
1, 3, 6, 9.90
1, 1, 12, 9.75
1, 2, 12, 9.75
1, 3, 12, 9.75
1, 1, 24, 9.50
1, 2, 24, 9.50
1, 3, 24, 9.50
1, 3, 36, 9.30
1, 2, 36, 9.30
1, 1, 36, 9.30


So depending on if my widget is available in certain sizes, the second column, then each product has an price for the size id and quantity at which the price break occurs.

I use this stored procedure to return the price or price range based on the input parameters entered.

CREATE PROCEDURE dbo.sp_GetPrice
@ProductID INT,
@QuantityID INT = NULL,
@SizeID INT = NULL
AS
BEGIN
SET NOCOUNT ON
IF @QuantityID IS NOT NULL AND @SizeID IS NULL -- WE ARE L0OKING FOR A SPECIFIC PRICE BUT DO NOT HAVE A SIZE SPECIFIED
SELECT DISTINCT Price AS 'Price'
FROM join_ProductSizeQuantityPrice
WHERE ProductID = @ProductID
AND Quantity = @QuantityID

IF @QuantityID IS NOT NULL AND @SizeID IS NOT NULL -- WE WANT THE EXACT PRICE FOR THE SIZE AND QUANTITY SPECIFIED
SELECT Price AS 'Price'
FROM join_ProductSizeQuantityPrice
WHERE ProductID = @ProductID
AND SizeID = @SizeID
AND Quantity = @QuantityID
IF @SizeID IS NULL AND @QuantityID IS NULL
SELECT MIN(Price) AS 'Price Range' -- WE ARE LOOKING FOR A PRICE RANGE
FROM join_ProductSizeQuantityPrice
WHERE ProductID = @ProductID
UNION ALL
SELECT MAX(Price)
FROM join_ProductSizeQuantityPrice
WHERE ProductId = @ProductID

END
GO

So everything works great, however, when a user orders an quantity amount like 7, 13, 26 - which is not part of the table - I want to give them the discount available to them for the price break appropriate.

For example if a customer orders 16 widgets of size 2 the price break threshold they have crossed is one dozen, however they have not yet reached the next one which is two dozen. Therefore I want to offer the price associated with one dozen widgets of size id which is: $9.75. Once I have this a simple calculation of this price * 16 units would give me a total but my question is, how do I elegantly design this quantity / right price per unit calculation?

-Brian

View 9 Replies View Related

SQL Server 2012 :: Calculate Failure Rates Of Systems Based On Cases Opened Through Support

Jun 5, 2014

I am trying to build a query which will be used in an automated report to calculate failure rates of systems based on cases opened through support. Here is where I am stuck. Some systems may have multiple cases opened within the same span of another cases however we would consider this one failure:

System ACase12013-07-11 13:17:09.0002013-07-15 12:05:03.000
System ACase22013-07-12 16:27:50.0002013-07-12 16:29:12.000
System ACase32013-07-12 17:30:32.0002013-07-12 17:40:11.000
System ACase42013-07-12 19:00:24.0002013-07-12 19:04:14.000
System ACase52013-10-01 18:02:23.0002013-10-01 18:11:26.000

Lets say System A generated those 5 cases however Case 2,3 and 4 all happened within the same period as Case 1 so those 4 cases should count as one failure so my end result should be

System ACase12013-07-11 13:17:09.0002013-07-15 12:05:03.000
System ACase52013-10-01 18:02:23.0002013-10-01 18:11:26.000

And that system should show me 2 failures. I was thinking of using a temp table but not sure if that is possible as I am stumped on how to compare the dates to be able to validate if they fall within the range of an older case and whether or not to include them into the new Temp Table.

View 8 Replies View Related

SQL 2012 :: Produce Report To Calculate No Of Days Based On User Input Start And End Date

Jan 5, 2015

I have to produce a report to calculate no of days based on user input start date and end date.

say for eg: in the tables I have emp name
user 'Phani' started work from - EStart 20/11/2014EEnd 10/01/2015 - total days --datediff
within his work period he did different roles:

PhaniMarketing (prSt Date) 20/11/2014prE date (28/11/2014) Total 9 days
PhaniAdmin (prSt Date) 29/11/2014prE date (20/12/2014) Total 22 days
PhaniCRM (prSt Date) 20/12/2014prE date (10/01/2015) Total 22 days
Total days 53 Days
for this :

[code]...

HOW CAN I USE Case statement to calculate days for given start date and end date. I have to include all three totals, 1 for Job dates, 2, subjobs dates, 3 cal of days for a requested period.

View 0 Replies View Related

Power Pivot :: Calculate Sales Quantity Since Last Inventory Count?

Sep 30, 2015

I have an inventory table with the following columns

[Item], [Quantity], [Date]

I have a sales table with the following columns

[Item], [Customer], [Quantity], [Date]

In addition to this I have a normal date table.

I want to create a measure that calculates

CurrentInventory:=LastInvenoryCountInTable-SalesQuantitySinceThen

I don't know where to start. Is this possible to do with DAX?

View 10 Replies View Related

SQL Server 2012 :: Calculate Number Of Days Based On Computer System Date And Due Date Row

Mar 18, 2014

I have a query to run a report where the results has a column named “Due Date” which holds a date value based on the project submission date.Now, I need to add 4 columns named, “45 Days Expectant”, “30 Days Overdue”, “60 Days Overdue” and “90 Days Overdue”.I need to do a calculation based on the “Due Date” and “System (I mean default computer date) Date” that if “System Date” is 45 days+ to “Due Date” than put “Yes” in “45 Days Expectant” row.

Also, if “Due Date” is less than or equal to system date by 30 days, put “Yes” in “30 Days Overdue” and same for the 60 and 90 days.how to write this Case Statement? I have some answers how to do it in SSRS (Report Designer) but I want to get the results using T-SQl.

View 2 Replies View Related

SQL Server 2008 :: Split Single Row Into Multiple Rows Based On Column Value (quantity)

Jan 30, 2015

Deciding whether or not to use a CTE or this simple faster approach utilizing system tables, hijacking them.

SELECT s.ORDER_NUMBER, s.PRODUCT_ID, 1 AS QTY, s.VALUE/s.QTY AS VALUE
FROM @SPLITROW s
INNER JOIN master.dbo.spt_values t ON t.type='P'
AND t.number BETWEEN 1 AND s.QTY

Just wanted to know if its okay to use system tables in a production environment and if there are any pit falls of using them ?

View 1 Replies View Related

Transact SQL :: Get Max Date From Table Where Quantity Require Big From Quantity Shipped?

May 8, 2015

I need sql query to select max date shipment where sum of quantity required > sum of quantity shipped from sales line table but i dont know how to make my sales line table as following

shipment date   quantity required  quantity shipped

07/05/2015          200                             100
07/05/2015          300                             300
07/05/2015          100                              50
06/05/2015          200                             100
06/05/2015          200                             200

Here the result of query i need is   max shipment date is 07/05/2015 and quantity required is  600 and quantity shipped is 450 so tat i must select this date because quantity Required is big from quantity shippedmy question How i write the query get result above in sql server 2005.

View 9 Replies View Related

Moved Stock Minus In Item Table To Stock In Itemmoment Table

Sep 11, 2007

 helo all...,i want to make procedure like:examplei have table: item (itemid,itemname,stock)orderdetail(no_order,itemid,quantity)itemmoment(itemid,itemname,stock)item table itemid    itemname    stock  c1        coconut         2  p1         peanut          2orderdetail tableno_order        itemid        quantity   1                  c1                5itemmoment tableitemid    itemname    stock  c1       coconut          0  p1       peanut            0 when customer paid, his quantity in orderdetail decrease stock in item table..so stock in item table became:itemid        itemname    stock  c1            coconut         -3  p1            peanut           2it's not good, because stock may not minus...so i want to move -3 to itemmoment table..so stock in item table became:itemid        itemname    stock  c1            coconut          0  p1            peanut           2and in itemmoment table became:itemid        itemname    stock  c1             coconut        3  p1             peanut          0my store procedure like:ALTER PROCEDURE [dbo].[orders](    @no_order as integer,    @itemid AS varchar(50),    @quantity AS INT)ASBEGIN    BEGIN TRANSACTION            DECLARE @currentStock AS INT                SET @currentStock = (SELECT [Stok] FROM [item] WHERE [itemid] = @itemid)        UPDATE [item]        SET            [Stock] = @currentStock - @quantity        WHERE            [itemid] = @itemid    COMMIT TRANSACTIONENDit's only decrease stock with quantity. i want move stock minus from item to itemmoment..can anyone add code to my store procedure?plss.. helpp.thxx....

View 2 Replies View Related

Calculate Age Based On Dob

Aug 26, 2004

hi all;

I have seen posts on numerous websites to get the age from a dob column I am faced with the same problem but get this error:

Server: Msg 403, Level 16, State 1, Line 1
Invalid operator for data type. Operator equals divide, type equals datetime.

when I run the following query:

SELECT ROUND((currentdate - DOB)/365.24,0) FROM FL1_A_Backup

All I need is a simple statement that calcualtes the age from the dob column(smalldatetime) then creates a new row which it puts the data into.
I have already created a CurrentDate column which has a (getdate()) value attached to it.

This is nothing fancy or complicated and I just need to figure out from the year I'm not really concerned about if the person has a bday tomorrow or so on.

I know I am probably doing something wrong with this query and am not shy to say that I have only been using ms sql for a couple of months (basic select statements).

View 14 Replies View Related

Calculate Value Based On Other Values For Use In SRS Report

Mar 10, 2008



I am trying to create a report in SRS that will calculate a Composite Score based on the Sum of other scores and then that Sum is divided by 12.


Here is a copy of the Query I have created to calculate the numbers I want to use, but when I create the expression in SRS the calculations don't come out correctly. The expression that I use in SRS is at the bottom of the Script.

Thanks in Advance


--6 Trait_03052008.sql

--Pull test scores for 6 Trait out of Campus for SRS reports.

SELECT s.lastname+','+' '+s.firstname AS Student, e.grade, sm.lastname+','+' '+sm.firstname AS Teacher, sc.name AS School,

t.name AS Test, t.code, ts.rawscore,

CASE WHEN t.name = '1 Ideas' AND ts.rawscore IS NOT NULL THEN CAST(ts.rawscore * 3 AS Numeric)END AS IComp,

CASE WHEN t.name = '2 Organization' AND ts.rawscore IS NOT NULL THEN CAST(ts.rawscore * 3 AS Numeric) END AS OComp,

CASE WHEN t.name = '3 Voice' AND ts.rawscore IS NOT NULL THEN CAST(ts.rawscore * 2 AS Numeric)END AS VComp,

CASE WHEN t.name = '4 Word Choice' AND ts.rawscore IS NOT NULL THEN CAST(ts.rawscore * 2 AS Numeric)END AS WComp,

CASE WHEN t.name = '5 Sentence Fluency' AND ts.rawscore IS NOT NULL THEN CAST(ts.rawscore AS Numeric) END AS SComp,

CASE WHEN t.name = '6 Conventions' AND ts.rawscore IS NOT NULL THEN CAST(ts.rawscore AS Numeric)END AS CComp

FROM testscore ts

JOIN student s ON s.personid = ts.personid

JOIN roster r ON r.personid = s.personid

JOIN test t ON t.testid = ts.testid

JOIN calendar ca ON ca.calendarid = s.calendarid

JOIN enrollment e ON e.enrollmentid = s.enrollmentid and e.calendarid = ca.calendarid

JOIN section se ON se.sectionid = r.sectionid

JOIN course c ON c.courseid = se.courseid AND c.calendarid = ca.calendarid

JOIN school sc ON sc.schoolid = s.schoolid

JOIN staffmember sm ON sm.personid = se.teacherpersonid AND sm.schoolid = ca.schoolid

WHERE t.code LIKE '6%' AND c.calendarid =50 AND c.homeroom = 1

GROUP BY s.lastName,s.firstName,e.grade,sm.lastName,sm.firstName,sc.name,t.name,t.code,ts.rawScore

ORDER BY [Student], t.code, t.name DESC


Expression being used in SRS to calculate the Composite Score.

=SUM(Fields!IComp.Value)+(Fields!OComp.Value)+(Fields!VComp.Value)+(Fields!WComp.Value)+(Fields!SComp.Value)+(Fields!CComp.Value)/12

View 4 Replies View Related

Calculate Update Time Based On Recordcount

Apr 10, 2008

I have a number of databases with large tables. I need to update them from time to time. I want to get the recordcount of the table and calculate based on that the amount of time it would take to update the table. Any idea who I can do this? I'm using coldfusion 8 with sql to do this. Any advice would be appreciate!

Thanks
Shuvi

View 2 Replies View Related

Transact SQL :: Calculate Average Based On A Scenario

Oct 30, 2015

Col1                      Col2       Col3          Col4
54763.00              21           0              0             
--Row1
59574.00              23           0              0             
--Row2
64085.00              20           0              0             
--Row3
0.0               0.00      0           0              0             
--Row4

I'm trying to calculate Average of Col1 of above table based on below scenario:

CASE WHEN all the columns in the above table are “0” (as highlighted) THEN I want AVERAGE of Col1 as (Row1+Row2+Row3)/3

ELSE if at least one of the column of highlighted row has value other than “0”, THEN I want the AVERAGE of Col1 to be (Row1+Row2+Row3+Row4)/4

View 7 Replies View Related

Transact SQL :: Calculate Data Based On Position

Jun 4, 2015

I have a table "PrintArea" with below table structure.

The Details column have " " separated data.

CREATE TABLE [dbo].[PrintArea](
[ID] [int] IDENTITY(1,1) NOT NULL,
[AccessDate] [datetime] NULL,
[IPAddress] [varchar](16) NULL,
[SerialNum] [varchar](256) NULL,
[Description] [varchar](256) NULL,
[Details] [varchar](2048) NULL,
)

This is how the data lookis like.

INSERT [dbo].[PrintArea] ([ID], [AccessDate], [IPAddress], [SerialNum], [Description], [Details]) VALUES (104280, CAST(0x0000A28A00A88310 AS DateTime), N'70.89.39.161', N'InSign-f529c824-85a6-4a64-8c59-e9f786d718f3-YM2AS31367,BFEBFBFF000306A9', N'Printing', N'Headboard_Insert_4
1
1
7938
5579

[Code] ...

I want to calculate totalAreaPrinted based on below formula from Details column.

View 2 Replies View Related

Disaster Recovery: Calculate DB Size Based On .dmp Files

Feb 7, 2000

I have a client with no backup of MASTERdb or Help_rev_devices, all I have is a couple of .dmp's of the production data. In order to run DISK REINIT I need to know the size of the database, is there any way of finding out the size of the database device, if all you have to go with is a backup dump file?

I know it won't be pretty.

`Ken

View 1 Replies View Related

Case Statement - Calculate No Of Days Based On User Input Start And End Date

Jan 5, 2015

I have to produce a report to calculate no of days based on user input start date and end date. I have tried to explain below.

say for eg: in the tables I have emp name
user 'Phani' started work from - EStart 20/11/2014EEnd 10/01/2015 - total days --datediff
within his work period he did different roles:

PhaniMarketing (prSt Date) 20/11/2014prE date (28/11/2014) Total 9 days
PhaniAdmin (prSt Date) 29/11/2014prE date (20/12/2014) Total 22 days
PhaniCRM (prSt Date) 20/12/2014prE date (10/01/2015) Total 22 days
Total days 53 Days

For this :

I calculated datediff + 1 and got sub jobs days BUT

say financial director wants to see Title of 'Sub Jobs' with 'Days' from 1st Dec to 31st Dec

so on paper I calulated as :

1-31 Dec 2014
PhaniMarketing NULL (Do not fall in Req Dt)
PhaniAdmin 20 (Deduct 2 days of Nov & calculated 20 days of Dec)
PhaniCRM 11 (Deduct 20 days of Nov and deduct 11 days of Jan so for Dec , we got 11 days)
Total days 31

HOW CAN I USE Case statement to calculate days for given start date and end date. I have to include all three totals, 1 for Job dates, 2, subjobs dates, 3 cal of days for a requested period.

View 4 Replies View Related

Need Help With Aging T-Script

Jun 28, 2007

I am tring to create a 30 60 90 day aging in my script I am getting errors  at the bold code below can some on look at this and tell me what I am doing wrong or what I am missing.
SELECT  ' L Detail by Company' as 'qtr',        COUNT(JOB.JOBID) as 'transcount',       COUNT(DISTINCT JOB.PATIENTID) as 'patient count',       SUM(JOB.LANGUAGE_TCOST) as 'lcost',       SUM(JOB.LANGUAGE_DISC_COST) as 'dlcost',       AVG(JOB.LANGUAGE_DISC) as 'avgLDisc',       SUM(JOB.LANGUAGE_TCOST) + SUM(JOB.LANGUAGE_DISC_COST) as 'LGrossAmtBilled',       SUM(JOB.LANGUAGE_TCOST) / COUNT(DISTINCT JOB.PATIENTID) as 'PatAvgL',       SUM(JOB.LANGUAGE_TCOST) / COUNT(JOB.JOBID) as 'RefAvgL',       SUM(JOB.LANGUAGE_DISC) as 'avgPercentDiscL',       JOB.JURISDICTION,PAYER.PAY_GROUPNAME,PAYER.PAY_COMPANY,PAYER.PAY_CITY,PAYER.PAY_STATE,PAYER.PAY_SALES_STAFF_ID,       JOB.INVOICE_DATE,JOB.PATIENTID,JOB.JOBOUTCOMEID,JOB.SERVICEOUTCOME,INVOICE_AR.INVOICE_NO,INVOICE_AR.INVOICE_DATE AS EXPR1,       INVOICE_AR.AMOUNT_DUE,INVOICE_AR.CLAIMNUMBER,PATIENT.LASTNAME,PATIENT.FIRSTNAME,PATIENT.EMPLOYERNAME,JOB_OUTCOME.DESCRIPTION,       SERVICE_TYPE.DESCRIPTION,PAT_SERVICES_HISTORY.LANG_TYPE,MASRECEIVL.MASRVDATE,MASRECEIVL.MASRCVAMOUNT,REFERRAL_SOURCE.REF_LASTNAME,       REFERRAL_SOURCE.REF_FIRSTNAME,REFERRAL_SOURCE.REF_PHONE,REFERRAL_SOURCE.REF_PHONE_EXT,REFERRAL_SOURCE.REF_FAX,REFERRAL_SOURCE.REF_EMAIL,JOB.INJURYDATE,JOB.APPT_DATE,  SUM(CASE WHEN (JOB_OUTCOME.DESCRIPTION = 'Completed with complaint') THEN 1 ELSE 0 END) AS 'CompletedWithcomplaintItems', SUM(CASE WHEN (JOB_OUTCOME.DESCRIPTION = 'Completed Successfully') THEN 1 ELSE 0 END) AS 'CompletedSuccessfullyItems', SUM(CASE WHEN (JOB_OUTCOME.DESCRIPTION = 'Completed with No Charge') THEN 1 ELSE 0 END) AS 'CompletedwithNoChargeItems', SUM(CASE WHEN (JOB_OUTCOME.DESCRIPTION = 'Completed with No Show') THEN 1 ELSE 0 END) AS 'CompletedwithNoShowItems', SUM(CASE WHEN (JOB_OUTCOME.DESCRIPTION = 'Completed with Situation') THEN 1 ELSE 0 END) AS 'CompletedWithSituationItems', SUM(CASE WHEN (JOB_OUTCOME.DESCRIPTION = 'Not Completed') THEN 1 ELSE 0 END) AS 'NotCompletedItems', SUM(CASE WHEN (JOB_OUTCOME.DESCRIPTION = 'Cancelled Prior to service') THEN 1 ELSE 0 END) AS 'CancelledPriortoserviceItems', SUM(CASE WHEN (JOB_OUTCOME.DESCRIPTION = 'Cancelled During Service') THEN 1 ELSE 0 END) AS 'CancelledDuringServiceItems', SUM(CASE WHEN (JOB_OUTCOME.DESCRIPTION = 'Awaiting for completion') THEN 1 ELSE 0 END) AS 'AwaitingforcpmpletionItems', SUM(CASE WHEN (JOB_OUTCOME.DESCRIPTION = 'Pending for review') THEN 1 ELSE 0 END) AS 'PendingforreviewItems',
 SUM(CASE WHEN (INVOICE_AR.INVOICE_DATE AS EXPR1  BETWEEN @dAgingDate-30 and @dAgingDate THEN MASRECEIVL.MASRCVAMOUNT Else 0 END) AS Age30, SUM(CASE WHEN (INVOICE_AR.INVOICE_DATE AS EXPR1  BETWEEN @dAgingDate-60 and @dAgingDate-31 THEN MASRECEIVL.MASRCVAMOUNT Else 0 END) AS Age60, SUM(CASE WHEN (INVOICE_AR.INVOICE_DATE AS EXPR1  BETWEEN @dAgingDate-90 and @dAgingDate-61 THEN MASRECEIVL.MASRCVAMOUNT Else 0 END) AS Age90
FROM JOB        INNER JOIN INVOICE_AR ON JOB.JOBID = INVOICE_AR.JOBID       LEFT OUTER JOIN PAYER ON PAYER.PAYERID = JOB.PAYERID       LEFT OUTER JOIN MASRECEIVL ON MASRECEIVL.INVOICE_NO = INVOICE_AR.INVOICE_NO       LEFT OUTER JOIN REFERRAL_SOURCE ON REFERRAL_SOURCE.REFERRAL_ID = JOB.ADJUSTERID       LEFT OUTER JOIN STATES ON JOB.JURISDICTION = STATES.INITIALS       LEFT OUTER JOIN PATIENT ON PATIENT.PATIENTID = JOB.PATIENTID       LEFT OUTER JOIN JOB_OUTCOME ON JOB_OUTCOME.JOB_OUTCOME_ID = JOB.JOBOUTCOMEID       LEFT OUTER JOIN SERVICE_TYPE ON SERVICE_TYPE.DESCRIPTION = JOB.SERVICEOUTCOME       LEFT OUTER JOIN PAT_SERVICES_HISTORY ON PAT_SERVICES_HISTORY.PATIENTID = JOB.PATIENTIDWHERE      (INVOICE_AR.AMOUNT_DUE > 0) AND (INVOICE_AR.INVOICE_DATE BETWEEN @startdate and @enddate)AND         (MONTH(INVOICE_AR.INVOICE_DATE) IN (1,2,3,4,5,6,7,8,9,10,11,12)) AND (PAYER.PAY_Company like '%' + @Company + '%') AND       (INVOICE_AR.INVOICE_NO like '%L')  AND (MASRECEIVL.MASRCVAMOUNT > 0)          Group By        JOB.JURISDICTION,        PAYER.PAY_GROUPNAME,        PAYER.PAY_COMPANY,        PAYER.PAY_CITY,        PAYER.PAY_STATE,        PAYER.PAY_SALES_STAFF_ID,        JOB.PATIENTID,        JOB.INVOICE_DATE,        JOB.JOBOUTCOMEID,        JOB.SERVICEOUTCOME,        INVOICE_AR.INVOICE_NO,        INVOICE_AR.INVOICE_DATE,        INVOICE_AR.AMOUNT_DUE,        INVOICE_AR.CLAIMNUMBER,        PATIENT.LASTNAME,        PATIENT.FIRSTNAME,        PATIENT.EMPLOYERNAME,        JOB_OUTCOME.DESCRIPTION,        SERVICE_TYPE.DESCRIPTION,        PAT_SERVICES_HISTORY.LANG_TYPE,        MASRECEIVL.MASRVDATE,        MASRECEIVL.MASRCVAMOUNT,        REFERRAL_SOURCE.REF_LASTNAME,        REFERRAL_SOURCE.REF_FIRSTNAME,        REFERRAL_SOURCE.REF_PHONE,        REFERRAL_SOURCE.REF_PHONE_EXT,         REFERRAL_SOURCE.REF_FAX,        REFERRAL_SOURCE.REF_EMAIL,        JOB.INJURYDATE,        JOB.APPT_DATE
Order By 'QTR' asc

View 3 Replies View Related

SQL Aging Report

Dec 21, 2005

Hello,
I have a table of current customers that im trying to get an aging report for but is not working correctly.




Current Day
Month To Date
Last Month Same Day

Last Month Total
Last Year to Date
 
here is a sample of what im doing
SELECT
 COUNT(CASE WHEN create_date > dateadd(yy, datediff(year, 1, getdate()), - 365) AND create_date <= DateAdd(year, - 1, DateAdd(day, 0, GetDate())) THEN create_date ELSE 0 END) AS LastYTD,  COUNT(CASE WHEN create_date > dateadd(yy, datediff(yy, 0, getdate()), 0) AND create_date <= DateAdd(day, + 1, GetDate()) THEN customer_ID ELSE 0 END)  as CurrentYTD
when i add the Current Day sql it gives me the same number as the rest of it which is wrong, it should be 0 based on my date.
 

View 4 Replies View Related

'aging' Tables

Jan 10, 2007

I'm about to create some mechanism for control both: size of given table andage of it's entries. I wish it to delete entries if older then X , or last nentries when table is bigger then Y .I need opinion if it will be good to use ddl trigger mechanism (SS2005), ormaybe someone would share another solution. It is supposed to be used onlyfor some tables like log table, not for each table in database, I don't wantto the mechanism decrease performance too much though.

View 3 Replies View Related

Query For A/R Aging Report

Aug 20, 2001

How can I write a query to output the balances of unpaid invoices into aging columns? I have invoices, lineitems, and payments tables. I have a query that will join the 3 tables to determine which invoices are unpaid. I need to write an aging report in Access 2000 with the unpaid invoices listed with the balance under the proper heading (ie:<30, 30-60, 60+). Any ideas on how to do that? I can write a query to pull one date segment at a time but I can't get them all into one query with different headings to base a report on. My customer had it working in Access 2000 but he upgraded to SQL Server 7 with an Access 2000 Project as a front end and we can't get it to work. It's driving me crazy! TIA!!!

View 2 Replies View Related

SQL 2012 :: How To Calculate The Distance In Miles

Oct 15, 2015

DECLARE @Latitude NUMERIC(9, 6), @Longitude NUMERIC(9, 6)

DECLARE @MyLatitude NUMERIC(9, 6), @MyLongitude NUMERIC(9, 6)
Set @Latitude = 42.329596;
Set @Longitude = -83.709286;
Set @MyLatitude = 42.430883;
Set @MyLongitude = -82.923642;

Question: How do we calculate the distance in miles between the 2 points.

View 5 Replies View Related

SQL 2012 :: Calculate (Number Of Days To Pay) Logic

Jun 24, 2014

How to write a query that calculate the number of days (approx) that it takes to a customer to pay an invoice.

Document Types

1 Payment
2 Invoice
3 Credit Memo
4 Finance Charge Memo
5 Reminder
6 Refund

There are three methods to consider when calculating the days to pay logic.

Method 1 - Simple : Look for Document Type 2 (Invoice), if "closed at date" > "posting date" then number of days = ("closed at date" - "posting date")

Method 2 - A Document Type 1 (payment) closes a Document Type 2 (Invoice)
For this method the formula would be: Payment Record (1) "posting date" - Invoice Record (2) "posting date"

Method 3 - An Invoice closes the payment.

On a payment entry “closed by entry no.” refers to an Invoice entry.

a. In our code we are not on the payment looking for the invoice, we are on the invoice.
i. Because of this we need to find the entry that our current invoiced has closed.

I am taking this from a page that has the pascal code that I need to translate to SQL.

IF (CustLedgEntry2."Document Type" = CustLedgEntry2."Document Type"::Invoice) AND
NOT CustLedgEntry2.Open
THEN
IF CustLedgEntry2."Closed at Date" > CustLedgEntry2."Posting Date" THEN
UpdateDaysToPay(CustLedgEntry2."Closed at Date" - CustLedgEntry2."Posting Date")

[Code] ....

I am also including create table and insert data scripts ...

View 9 Replies View Related

SQL 2012 :: How To Calculate Date Difference In Months

Jan 23, 2015

I would like to calculate difference between end_date and current date in Months.And also how we can calculate the sum of difference in months between start_date and end_date for each ID?

CREATE TABLE datedifference (
id INT
,start_date INT
,end_date INT
)
INSERT INTO datedifference VALUES (10,20091202,20100629)
INSERT INTO datedifference VALUES (20,20071202,20090330)
INSERT INTO datedifference VALUES (30,20051202,20101031)

View 6 Replies View Related

SQL Server 2012 :: Calculate Total Between Two Columns

Sep 14, 2015

I have update schema and I upload image with my desire result.

CREATE TABLE #NONAMETABLE(
sinGroup NVARCHAR(10)
,column1 INT
,column2 int

[Code] .....

View 7 Replies View Related

SQL Server 2012 :: Calculate EndDate From Subsequent StartDate

Jul 28, 2014

Here is sample data I am working with:

Create table cattimelines (categoryID int, EffectiveDate datetime, CategoryValue varchar(11))

INSERT INTO cattimelines(categoryID, EffectiveDate, CategoryValue) VALUES(1000, '2014-01-01', 'A')
INSERT INTO cattimelines(categoryID, EffectiveDate, CategoryValue) VALUES(1000, '2014-02-01', 'B')
INSERT INTO cattimelines(categoryID, EffectiveDate, CategoryValue) VALUES(1000, '2014-04-01', 'C')
INSERT INTO cattimelines(categoryID, EffectiveDate, CategoryValue) VALUES(1000, '2014-07-01', 'A')

I need to calculates a term date for each record which will be 1 day before the effective date of any new record, thus:

CATEGORYIDEFFECTIVEDATETERMDATECATEGORYVALUE

10002014-01-012014-01-31A
10002014-02-012014-03-21B
10002014-04-012014-06-30C
10002014-07-01NULLA

View 3 Replies View Related







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