Expressions in SSRS - sql

I am trying to get a certain expression to work in SSRS. My query pulls up a category, sub category and a count statement grouped by the sub category for tracking incidents. This is my query:
SELECT Category, Sub_Category, CAST(Count(incident) AS decimal) As Total_Incidences
FROM service_req
GROUP BY Sub_Category
I am trying to break these down into percentages, for example a specific sub category accounts for 67% of a certain main category incidences, and would also like to have a percentage of main categories vs total calls, i.e. 12% of all incidences are from this certain category.
My math is not coming out right when trying to make it work, and I cant figure out the best way to do this. Any suggestions? I know I have to divide the count statement by the sum of all incidences in the subcategory to get that percentage, and all sub category sums by the total incidences to get the first percentage however I am not sure how to use a group by with these expressions (or even if I can) to get this to work. Any help would be appreciated!

The problem can be solved not in SSRS but rather in the query that returns data. You need 2 separate groupings - one by category, another by category/subcategory combination. Then you can join them like this:
SELECT Sub.Category, Sub.Sub_Category, Sub.Total_IncidencesSub*100/Main.Total_IncidencesMain AS Percentage FROM
(SELECT Category, CAST(Count(incident) as DECIMAL) As Total_IncidencesMain
FROM service_req
GROUP BY Category) Main
INNER JOIN
(SELECT Category, Sub_Category, CAST(Count(incident) AS DECIMAL) As Total_IncidencesSub
FROM service_req
GROUP BY Category, Sub_Category) Sub
ON Main.Category = Sub.Category
Here is live demo: http://sqlfiddle.com/#!3/eee07/7

Related

Get the product of two values from two different tables

If anyone can help me figure out where I am going wrong with this SQL that would be great. Please see my attempt to answer it below. I have answer how I think it should be answered but I am very confused by the exam advice below, which says I should use a SUM function? I have googled this and I do not see how a SUM function can help here when I need get the product of two values in this case. Or am I missing something major?
Question: TotalValue is a column in Order relation that contains derived data representing total value (amount) of each order. Write a SQL SELECT statement that computes a value for this column.
My answer:
SELECT Product.ProductPrice * OrderLine.QuantityOrdered AS Total_Value
FROM Product,
OrderLine
GROUP BY Product;
Advice from exam paper:
This is a straightforward question. Tip: you need to use the SUM function. Also, note that you can take the sum of various records set using the GROUP BY clause.
Ok your question became a lot clearer once I clicked on the the hyperlink (blue text).
Each order is going to be made up of a quantity of 1 or more products.
So there could be 3 Product A and 5 Product B etc.
So you have to get the total for each product which is your Price * Quantity, but then you need to add them all together which is where the SUM comes in.
Example:
3 * ProductA Price (e.g. €5) = 15
5 * ProductB Price (e.g. €4) = 20
Total Value = 35
So you need to use the Product, Order and OrderLine tables.
Something like (I haven't tested it):
SELECT SUM(Product.ProductPrice * OrderLine.QuantityOrdered) FROM Product, Order, OrderLine
WHERE Order.OrderID = OrderLine.OrderID
AND Product.ProductID = OrerLine.ProductID
GROUP BY Order.OrderID
This should return rows containing the totalValue for each order - the GROUP BY clause causes the SUM to SUM over each group - not the entire rows.
For a single order you would need add (before the GROUP BY) "AND Order.OrderID = XXXXX" where XXXXX is the actual orders OrderId.

How to find the sum of a column generated from a query

So, I'm im doing a ticket style database and i'm trying to find the sum of the tickets generated from this. I have attached my query below and the result of it
QUERY RESULT
SELECT Price, TicketID, Ticket.TicketType
FROM Price, Ticket
WHERE Price.TicketType = Ticket.TicketType
;
In the picture, I am trying to get a total for all of the prices that you see in there, each ticketID is a new ticket sold. I can click the totals button in access and it puts a total below it, but I need the total done in the query, so I am wondering how I could do this.
First, learn to use proper join syntax. Commmas in the FROM clause are simply an archaic way to represent a join.
From what you say, you want sum():
SELECT SUM(Price)
FROM Price JOIN
Ticket
ON Price.TicketType = Ticket.TicketType;
This may or may not do exactly what you want. It answers the question quite specifically.
Use the SUM function:
http://www.w3schools.com/sql/sql_func_sum.asp
I think this can help

Select inside select

A newbie here. So please be kind :-)
I have 2 Tables namely Item & Item Entries.
Relation is: Item.No = ItemEntries.No.
In Item Entries Table I have Columns as Qty, Entry type, Purchase Amount, Sales Amount
I like to have a report which shows as below,
Item No. | Opening Quantity | Purchase Amount | Sales Amount
To calculate Opening Inventory I summed up the quantity field and the result is as expected. No problem in that. Now From that dataset I like to run a sub query which Calculates/Sum the Purchase amount for an Item that is a part of first dataset and similarly for Sales Amount.
Select(Item No.,Sum(IE.Quantity) As Quantity, Select(......Purchase Amount),Select(....Sales Amount)
I hope I was able to clear my doubts to you guys.
Something like :
SELECT ItemNo, sum(quantity), purchaseAmount, SalesAmount FROM Item i INNER JOIN ItemEntities ie on i.no = ie.no GROUP BY ItemNo, PurchaseAmount, SalesAmount;
I believe (if I understand what you want) that this is the solution to your problem
Select Item.No ,
Sum(IE.Quantity) As Quantity,
(Select(......Purchase Amount)) As ColumnName1 ,
(Select(....Sales Amount)) As ColumnName2
From your need to "sum the purchase amount for an item that is part of the first dataset and similarly for Sales Amount" I think what you're trying to achieve is one row for each item on the Item table with a sum for each of the Qty, Sales Amount and Purchase Amount. If so, then you can simply use a 'group by' clause which groups results together which have matching values for the columns specified.
SELECT I.no, SUM(IE.qty), SUM(IE.purchase_amount), SUM(IE.sales_amount)
FROM item I JOIN item_entries IE
ON I.no = IE.no
GROUP BY I.no;
See the group_by_clause for more details and some examples.
N.B. The join from the item tables isn't strictly required in this example, but if you're producing a report I suspect you might want to get things like a description - in which case you'll need to add those columns to the group by clause too.
You might need the sum of three columns from
ItemEntries table(Qty,PurchaseAmount,SalesAmount) for each Item.No
Select A.No,
Sum(B.Qty),
Sum(B.Purchaseamount),
Sum(B.Salesamount)
From Item A,
Itementries B
Where A.No = B.No
Group By A.No;

Your Query does not include the specified expression, how to fix it?

I don't understand why my sql is not running,
it pop out a window say
"Your query does not include the specified expression ' SUM(SaleRecord.Number)*(product.Price' as part of an aggregate function"
SELECT SUM(SaleRecord.Number)*(Product.Price) AS TotalIncome
FROM Product, SaleRecord
WHERE Product.ProductID=SaleRecord.SaleProduct;
Product.Price is not part of the aggregate. Presumably, you intend:
SELECT SUM(SaleRecord.Number * Product.Price) AS TotalIncome
FROM Product INNER JOIN
SaleRecord
ON Product.ProductID=SaleRecord.SaleProduct;
Note that I also fixed the archaic join syntax.
You asked in my previous answer:
"thank you, I just make some mistake, now it is working. And sorry to
bother you more, I want to select the product who sell the most out,
how can I do it, I try to add MAX(xxx) on it, and it don't work"
Now, I am by no means an expert, but there are two processes going on. Your language is confusing so I'm going to assume you want to know which product sells the most in $$ terms (rather than count. For example, you might sell 1,000 $0.50 products, equallying $500 total sales, or 10 $500 products, totallying $5000. If you want the count or the dollar value, then the method changes slightly).
So the first process is to get the total sales of each product, which I outlined above. Then you want to nest that inside a second query, where you then select the max. I'll give you the code and then explain it:
SELECT ProductID, MAX(TotalSale)
FROM (
SELECT P.ProductID, SUM(S.Number)*P.Price AS TotalSale
FROM Products as P, SaleRecords as S
WHERE product.Productid = SaleRecord.SaleProduct
GROUP BY Product.ProductID
)
It's easiest to imagine this as querying a query. Your first query is in the FROM() statement. That will run and give you the output of total sale per product. Then the second query is ran (the top most SELECT line) that selects the productID and the sale amount that is the largest among all the products.
Your teacher may not like this since nesting queries is a little advanced (though completely intuitive IMO). Hopefully this helps!
You brackets are wrong - for each row you want to multiply the price by the number, and only then sum them:
SELECT SUM(SaleRecord.Number * Product.Price) AS TotalIncome
FROM Product, SaleRecord
WHERE Product.ProductID = SaleRecord.SaleProduct;
You have a bracket error:
SELECT SUM(SaleRecord.Number * Product.Price) AS TotalIncome
FROM Product INNER JOIN
SaleRecord ON Product.ProductID = SaleRecord.SaleProduct;
This is because you're not indicating which column to group by. The line you wrote is:
SUM(SaleRecord.Number) * Product.Price
Which sums all of the sale quantities (regardless of differences in product ID) and multiplies it by the price right? Well what if you have multiple products with different prices? Basically, you are doing a one to many match, where you have a total that is the sum of all the sales, multiplied by multiple prices. What you need is a group by command. I would modify your code to say:
SELECT Product.ProductID, SUM(SaleRecord.Number)*Product.Price AS TotalSales
FROM Product, SaleRecord
WHERE product.Productid = SaleRecord.SaleProduct
GROUP BY Product.ProductID
That should take care of it, telling the dbms to group each product together, sum the number of sales and then multiply by the price of that product.
You can nest that inside another query to get total Income:
SELECT SUM(TotalIncome)
FROM ( **the above code here)
EDIT: Or you can do it like the ways listed above where your query creates a TotalIncome for each ORDER, and then sums them all together. my way creates a total sale for each PRODUCT and then sums all the products

Calculate First Time Buyer and Repeating Buyers using MAQL Queries in GOOD-DATA platform

I have been recently working with GOOD-DATA platform. I don't have that much experience in MAQL, but I am working on it. I did some metric and reports in GOOD-DATA platform. Recently I tried to create a metric for calculating Total Buyers,First Time Buyers and Repeating Buyers. I created these three reports and working perfect.But when i try to add a order date parent filter the first time buyers and repeating buyers value getting wrong. please have Look at Following queries.
I can find out the correct values using sql queries.
MAQL Queries:
TOTAL ORDERS-
SELECT COUNT(NexternalOrderNo) BY CustomerNo WITHOUT PF
TOTAL FIRSTTIMEBUYERS-
SELECT COUNT(CustomerNo) WHERE (TOTAL ORDER WO PF=1) WITHOUT PF
TOTAL REPEATINGBUYERS-
SELECT COUNT(CustomerNo) WHERE (TOTAL ORDER WO PF>1) WITHOUT PF
Can any one suggest a logic for finding these values using MAQL
It's not clear what you want to do. If you could provide more details about the report you need to get, it would be great.
It's not necessary to put "without pf" into the metrics. This clause bans filter application, so when you remove it, the parent filter will be used there. And you will probably get what you want. Specifically, modify this:
SELECT COUNT(CustomerNo) WHERE (TOTAL ORDER WO PF>1) WITHOUT PF
to:
SELECT COUNT(CustomerNo) WHERE (TOTAL ORDER WO PF>1)
The only thing you miss here is "ALL IN ALL OTHER DIMENSIONS" aka "ALL OTHER".
This keyword locks and overrides all attributes in all other dimensions—keeping them from having any affect on the metric. You can read about it more in MAQL Reference Guide.
FIRSTTIMEBUYERS:
SELECT COUNT(CustomerNo)
WHERE (SELECT IFNULL(COUNT(NexternalOrderNo), 0) BY Customer ID, ALL OTHER) = 1
REPEATINGBUYERS:
SELECT COUNT(CustomerNo)
WHERE (SELECT IFNULL(COUNT(NexternalOrderNo), 0) BY Customer ID, ALL OTHER) > 1