How Can I Sum Vat in a column in sql server 2008? - sql

suppose i have the following table
CREATE TABLE #ResultTable (NettAmount money, GrossAmount money,TotalVat money)
Given a gross amount eg=250 I know that vat is at 17.5%
How Do i calculate the totalVat?
Thanks for any suggestions

INSERT #ResultTable
(NettAmount, GrossAmount, TotalVat)
SELECT
NettAmount, GrossAmount, GrossAmount * 17.5 /100
FROM
SourceTable
It's unclear what you want to do, sorry...

devnet247 - have a 2nd table that contains the valid date tracked VAT rate along the lines of:
vat_rate | vat_type | stt_date | end_date
-----------------------------------------
0.175 | 1 | 20100101 | null
vat_type | description
-----------------------------------------
1 | standard rate
2 | reduced rate
3 | zero rate
and then join on that table where the invoice date is valid for the row. your final sql would be along the lines of
SELECT SUM(NettAmount * vat_rate as total_vat) from #ResultTable r1, vat_table v1
where r1.invoice_date between v1.stt_date and v1.end_date
and r1.vat_type = v1.vat_type
anyway, if you were tracking the vat that is :)
jim
[edit] - if you were to use a second table, i'd suggest extending that to a 3rd - vat_type table, as vat rates vary across products as well as time. see http://www.hmrc.gov.uk/vat/forms-rates/rates/rates.htm#1

SELECT SUM(GrossAmount) * 17.5 /117.5 AS VATAmount
FROM SourceTable
Bearing in mind that (UK) VAT is due to increase to 20% from January 2011, it would be a good idea to follow Jim's suggestion of a date-tracked VAT rate lookup table.

Related

SQL - Monthly cumulative count of new customer based on a created date field

Thanks in advance.
I have Customer records that look like this:
Customer_Number
Create_Date
34343
01/22/2001
54554
03/03/2020
85296
01/01/2001
...
I have about a thousand of these records (customer number is unique) and the bossman wants to see how the number of customers has grown over time.
The output I need:
Customer_Count
Monthly_Bucket
7
01/01/2021
9
02/01/2021
13
03/01/2021
20
04/01/2021
The customer count is cumulative and the Monthly Bucket will just feed the graphing package to make a nice bar chart answering the question "how many customers to we have in total in a particular month and how is it growing over time".
Try the following SELECT SQL with a sub-query:
SELECT Customer_Count=
(
SELECT COUNT(s.[Create_Date])
FROM [Customer_Sales] s
WHERE MONTH(s.[Create_Date]) <= MONTH(t.[Create_Date])
), Monthly_Bucket=MONTH([Create_Date])
FROM Customer_Sales t
WHERE YEAR(t.[Create_Date]) = ????
GROUP BY MONTH(t.[Create_Date])
Where [Customer_Sales] is the sales table and ??? = your year

SSAS Standard Edition - Getting Last Value from Fact Table at Transaction Grain

Background
Hi! I'm trying to work with a non-additive measure in SSAS 2008R2 Standard Edition knowing that semi-/non-additive measures don't work right out of the box in this edition.
I'm trying to calculate a last price invoiced from a fact table that looks something like this (sorry if this isn't the right way to create tables in these posts!):
| Invoice No | Invoice Line | DateId | ProductId | Unit Price |
|------------|--------------|----------|-----------|------------|
| 1 | 1 | 20160901 | 2 | 10 |
| 4 | 2 | 20160901 | 2 | 10 |
Unit Price is defined as a Last Child measure. Invoice No & Invoice Line are used to generate a Degenerate Dimension. Following Chris Webb's blog post, Last Ever Non Empty – a new, fast MDX approach, I can grab the last unit price across dates with no problem.
Problem
However, when one item has two records in the fact table for the same day--like the table above--the Unit Prices of each record still get aggregated when browsing the cube using the Date Dimension. Rather than show $10 on 2016-09-01, my cube is returning $10 + $10 = $20.
Solutions?
This post describes what sounds like the same problem and solves it by adding Hours / Seconds / Milliseconds to the Date dimension. Are there any other ways to handle this situation without modifying the Date dimension?
I'm a complete novice with MDX, but my hope is that it can help. Is there an MDX calculation that can somehow retrieve the unit price from the current Date member that has a [Invoice No] record rather than perform an aggregation at the [ALL] level?
I could change the grain of my fact table to be sales by day and handle all the calculations in TSQL where I feel much more comfortable, but that goes counter to what I've read from Ralph Kimball about Dimensional Modeling and trying to keep the fact table at the lowest possible grain.
I could also handle this in the underlying SQL tables during the ETL process using ROW_NUMBER() and then creating a MIN or MAX measure in SSAS.
Finally, I could calculate the Unit Price as an average by dividing Extended Price / Quantity, but it would be great to retrieve the actual price of the last invoice on a day if possible
Thank you!
If you want to get last ever price:
Select
Tail(
NonEmpty(
{
[DateId].[DateId].[DateId].Members *
[Invoice Line].[Invoice Line].[Invoice Line].Members *
[Invoice No ].[Invoice No ].[Invoice No ].Members *
[ProductId].[ProductId].[ProductId].Members *
[Unit Price].[Unit Price].[Unit Price].Members
},
[Measures].[Invoice Count]
),
1
) on 1,
[Measures].[Invoice Count] on 0
From [YourCube]
If you need the same per customer, you may want to use the Generate() function:
Select
Generate(
[CustomerId].[CustomerId].[CustomerId].Members,
Tail(
NonEmpty(
{
[CustomerId].[CustomerId].CurrentMember *
[DateId].[DateId].[DateId].Members *
[Invoice Line].[Invoice Line].[Invoice Line].Members *
[Invoice No ].[Invoice No ].[Invoice No ].Members *
[ProductId].[ProductId].[ProductId].Members *
[Unit Price].[Unit Price].[Unit Price].Members
},
[Measures].[Invoice Count]
),
1
)
) on 1,
[Measures].[Invoice Count] on 0
From [YourCube]
In sake of performance I'd recommend to add a measure YYYYMMDDPP-style with the MAX aggregation. Where YYYYMMDD is a date code and PP is a price value. For example:
| Invoice No | Invoice Line | DateId | ProductId | Unit Price | DatePrice |
|------------|--------------|----------|-----------|------------|------------|
| 1 | 1 | 20160901 | 2 | 10 | 2016090110 |
| 4 | 2 | 20160901 | 2 | 10 | 2016090110 |
And it will return a max value. In your case it's 2016090110. In order to get only price you'll need an extra calculated measure:
With
Member [Measures].[Last Price] as
Right([Measures].[MaxDatePrice],2)
Select [Measures].[Last Price] on 0
From [BI Fake]
You may want to expend PP size. It depends on your Price range.
Edit: Since your static size of price is 7, you need the following steps:
Create a DatePrice field in YYYYMMDDPPPPPPP format:
[PriceDate] =
year([DateId]) * 10000000000 +
month([DateId]) * 100000000 +
day([DateId]) * 10000000
+ [Unit Price]
Create a calculated measure:
Cint(Right([Measures].[MaxDatePrice],7))
Cint will convert 0000010 into 10.

Two tables, Three prices, Different periods, What can i do?

I have tried and failed to solve this puzzle, and now im looking for some nice help if anyone is out there. Explanation:
First table consists of the original price on a item.
Table1 (Sales_Data):
+---------+----------+-------+------------+
| Item_Id | Store_Id | Price | Sales_Date |
+---------+----------+-------+------------+
Second table consists of two prices
one is if a store has another price on the item and this has a 0 value in To_Date
because this price should last forever.(Lets call this forever price)
one is if a store has another price on a item for just a period (02.03.2014-10.03.2014) lets call this discount
both prices is stored in Price, but the dates are the big difference.
Table2 (Discount_Data):
+---------+----------+-------+------------+
| Item_Id | Store_Id | Price | Sales_Date |
+---------+----------+-------+------------+
Now to the big Q:
Forever price should always overwrite original price
Discount price should always overwrite original/or forever price for the exact period
Item_Id, and Store_Id has to be the same.
How can i go forward to solve this? Can anyone help me on the way?
I hate to make an assumption, but it appears your second table should include two more columns, From_Date and To_Date. I will alias Discount_Data forever price as ddf and Discount_Data period price as ddp
select sd.Item_Id,
sd.Store_Id,
sd.Price as OriginalPrice,
coalesce(ddd.Price,ddf.Price,sd.Price) as UpdatedPrice
from Sales_Data sd
left join Discount_Data ddf
on sd.Item_Id=ddf.Item_Id
and sd.Store_Id=ddf.Store_Id
and sd.Sales_Date >= ddf.From_Date
and ddf.To_Date=0
left join Discount_Data ddp
on sd.Item_Id=ddp.Item_Id
and sd.Store_Id=ddp.Store_Id
and sd.Sales_Date between ddp.From_Date and ddp.To_Date
Hope that helps.

sql DB calculation moving summary‏‏‏‏‏

I would like to calculate moving summary‏‏‏‏‏:
Total amount:100
first receipt: 20
second receipt: 10
the first row in calculation column is a difference between total amount and the first receipt: 100-20=80
the second row in calculation column is a difference between the first calculated_row and the first receip: 80-10=70
The presentation is supposed to present receipt_amount, balance:
receipt_amount | balance
20 | 80
10 | 70
I'll be glad to use your help
Thanks :-)
You didn't really give us much information about your tables and how they are structured.
I'm assuming that there is an orders table that contains the total_amount and a receipt_table that contains each receipt (as a positive value):
As you also didn't specify your DBMS, this is ANSI SQL:
select sum(amount) over (order by receipt_nr) as running_sum
from (
select total_amount as amount
from orders
where order_no = 1
union all
select -1 * receipt_amount
from the_receipt_table
where order_no =
) t
First of all- thanks for your response.
I work with Cache DB which can be used both SQL and ORACLE syntax.
Basically, the data is locaed in two different tables, but I have them in one join query.
Couple of rows with different receipt amounts and each row (receipt) has the same total amount.
Foe example:
Receipt_no Receipt_amount Total_amount Balance
1 20 100 80
1 10 100 70
1 30 100 40
2 20 50 30
2 10 50 20
So, the calculation is supposed to be in a way that in the first receipt the difference calculation is made from the total_amount and all other receipts (in the same receipt_no) are being reduced from the balance
Thanks!

MySQL Group by Query but with one query i need to convert Currency Rate & merge Result [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have Table with Field
id | Customer | Currency Type | Sales Amt | Date
=====================================================
1 | ClientA | Dollar | 100$ | Timestamp
2 | ClientB | Rupees | 1500Rs | Timestamp
I am trying query like "Select Currency Type, Sum(Sales Amt) from Table where Date between start and End group by Currency Type"
But i want to first calculate All Rupees amt first and then merge them with Dollar type.
Sum(Sales Amt)*45(Conversion rate) where currency='rupees"
So in Result ill get only one Currency Type that is Dollar Amt so i can display reports on that basis.
Can it be possible? pls any one help me making this kind query or any otherway out.
Thanks
You can use a searched CASE statement to determine for each record if you need to convert it to dollars or not.
SELECT SUM(CASE [Currency Type]
WHEN 'Rupees' THEN [Sales Amt] * 45
WHEN 'Dollar' THEN [Sales Amt]
WHEN 'Other' THEN [Sales Amt] * ???
ELSE [Sales Amt]
END)
FROM Table
WHERE Date BETWEEN Start and End
Create a table CurrencyConvertTable
with following table structure and data
| CurrencyType | CurrencyConvertRate |
======================================
| Dollar | 1 |
| Rupees | 45 |
Noq query like this..
Select CurrencyType
,Sum(SalesAmt*CurrencyConvertRate)
from MainTable mt
JOIN CurrencyConvertTable ct
ON mt.CurrencyType = ct.CurrencyType
where Date between start and End
group by CurrencyType
Best way to handle more currency types..
I would suggest an own table for the currency conversion factors.
conversion_id source target factor
1 Rupees Dollar 45.0
2 Dollar Dollar 1.0
Now you can join the currency conversion table and calculate the sum dynamically without the use of a CASE WHEN END construct.
It would be better if you also design a currency table and use only currency ids.