SalesForce SOQL highest number from size column - salesforce

i'm new to SOQL and SF, so bear with me :)
I have Sales_Manager__c object tied to Rent__c via Master-Detail relationship. What i need is to get Manager with highest number of Rent deals for a current year. I figured out that the Rents__r.size column stores that info. The question is how can i gain access to the size column and retrieve highest number out of it?
Here is the picture of query i have
My SOQL code
SELECT (SELECT Id FROM Rents__r WHERE StartDate__c=THIS_YEAR) FROM Sales_Manager__c

Try other way around, by starting the query from Rents and then going "up". This will let you sort by the count and stop after say top 5 men (your way would give you list of all managers, some with rents, some without and then what, you'd have to manually go through the list and find the max).
SELECT Manager__c, Manager__r.Name, COUNT(Id)
FROM Rent__c
WHERE StartDate__c=THIS_YEAR
GROUP BY Manager__c, Manager__r.Name
ORDER BY COUNT(Id) DESC
LIMIT 10
(I'm not sure if Manager__c is the right name for your field, experiment a bit)

Related

Is there a way to sum an entire quantity in SQL with unique values

I am trying to get a total summation of both the ItemDetail.Quantity column and ItemDetail.NetPrice column. For sake of example, let's say the quantity that is listed is for each individual item is 5, 2, and 4 respectively. I am wondering if there is a way to display quantity as 11 for one single ItemGroup.ItemGroupName
The query I am using is listed below
select Location.LocationName, ItemDetail.DOB, SUM (ItemDetail.Quantity) as "Quantity",
ItemGroup.ItemGroupName, SUM (ItemDetail.NetPrice)
from ItemDetail
Join ItemGroupMember
on ItemDetail.ItemID = ItemGroupMember.ItemID
Join ItemGroup
on ItemGroupMember.ItemGroupID = ItemGroup.ItemGroupID
Join Location
on ItemDetail.LocationID = Location.LocationID
Inner Join Item
on ItemDetail.ItemID = Item.ItemID
where ItemGroup.ItemGroupID = '78' and DOB = '11/20/2019'
GROUP BY Location.LocationName, ItemDetail.DOB, Item.ItemName,
ItemDetail.NetPrice, ItemGroup.ItemGroupName
If you are using SQL Server 2012 , you can use the summation on partition to display the
details and aggregates in the same query.
SUM(SalesYTD) OVER (ORDER BY DATEPART(yy,ModifiedDate)),1)
Link :
https://learn.microsoft.com/en-us/sql/t-sql/functions/sum-transact-sql?view=sql-server-ver15
We can't be certain without seeing sample data. But I suspect you need to remove some fields from you GROUP BY clause -- probably Item.ItemName and ItemDetail.NetPrice.
Generally, you won't GROUP BY a column that you are applying an aggregate function to in the SELECT -- as in SUM(ItemDetail.NetPrice). And it is not very common, in my experience, to GROUP BY columns that aren't included in the SELECT list - as you are doing with Item.ItemName.
I think you need to go back to basics and read about what GROUP BY does.
First of all welcome to the overflow...
Second: The answer is going to be "It depends"
Any time you aggregate data you will need to Group by the other fields in the query, and you have that in the query. The gotcha is what happens when data is spread across multiple locations.
My suggestion is to rethink your problem and see if you really need these other fields in the query. This will depend on what the person using the data really wants to know.
Do they need to know how many of item X there are, or do they really need to know that item X is spread out over three sites?
You might find you are better off with two smaller queries.

SQL column update to solve data quality issue

I am unable to figure out how to write 'smart code' for this.
In this case I would like the end result for the first two case to be:
product_cat_name
A_SEE
A_BEE
Business is rule is such that one product_cat_name can belong to only one group but due to data quality issues we sometimes have a product_cat_name belonging to 2 different groups. As a special case in such a situation we would like to append group to the product_cat_name so that product_cat_name becomes unique.
It sounds so simple yet I am cracking my head over this.
Any help much appreciated.
Something like this:
with names as (
select prod_cat_nm , prod_cat_nm+group as new_nm from (query that joins 3 tables together) as qry
join
(Select prod_cat_nm, count(distinct group)
from (query that joins 3 tables together) as x
group by
prod_cat_nm
having count(distinct group) > 1) dups
on dups.prod_cat_nm = qry.prod_cat_nm
)
SELECT prod_cat_nm, STRING_AGG(New_nm, '') WITHIN GROUP (ORDER BY New_Nm ASC) AS new_prod_cat_nm
FROM names
GROUP BY prod_cat_nm;
I've used the 2017 STRING_AGG() here as its shortest to write - But you could easily change this to use Recursions or XML path
It is simple if you break it down into small pieces.
You need to UPDATE the table obviously, and change the value of product_cat_name. That's easy.
The new value should be group + product_cat_name. That's easy.
You only want to do this when a product_cat_name is associated with more than one group. That's probably the tricky part, but it can also be broken down into small pieces that are easy.
You need to identify which product_cat_names have more than one group. That's easy. GROUP BY product_cat_name HAVING COUNT(DISTINCT Group) > 1.
Now you need to use that to limit your UPDATE to only those product_cat_names. That's easy. WHERE product_cat_name IN (Subquery using above logic to get PCNs that have more than one Group).
All easy steps. Put them together and you've got your solution.

Summing up values from one column into one row on a different table when joining

I've only had a (frustrating) couple days experience with SQL Server, and I need some help, since I cant find anything related to my question when searching.
For background info, I'm working in an accountancy, and right now I'm trying to create a table for balance statements to use in crystal reports. Each invoice has multiple items, but for the statement I need to sum them all up with the invoice reference being the information that links the group of data that needs to be summarised.
So, what I need is to pull information from one table (dbo.SalesInvItems), this information including the date (InvDate), the due date (InvDueDate), and the customer name (CustomerName). This information stays the same with the Invoice Reference (InvRef), and it's what I want to use to link the two tables.
For example, Invoice Reference: 1478 will always have the date 14/05/18, the due date: 14/06/18 and the customer name: Pen Sellers Ltd.
The same Invoice Reference is used by multiple rows, but the only thing that changes (that I need) is the Invoice Item Total (InvItemTotal).
For example, the one reference will always be addressed to Pen Sellers, but one item has the Total as £13 and another item using the same reference is £20.
The Invoice Item Total is what I need to sum up. I want to add all the Invoice Item Total's together that have the same Invoice Reference, while joining the tables.
Sales Invoices
So when I've inserted the references into the table (sorry they're not the same in both pictures, I was having problems making examples and I made a mistake), I want to grab the information from the Invoice table to fill it in, going from this...
Pre Solution
To this...
Desired Result
The desired location is a table called dbo.Statement.
1.Is this even possible to do?
2.How would I go about doing this?
3.Is there a method I could use that would make sure that every time I insert an Invoice Reference into the Statement table, it would automatically pull out the data needed from the Invoice Table?
If any additional information is needed, just say and I'll do my best to provide it, I have never asked a question on here before and I'm new to SQL Server and coding in general.
Im using SQL Server Management Tool 2017
Thank You
Select item.InvRef
, item.CustomerName
, item.InvDate
, item.InvDueDate
, Sum(item.InvItemTotal) InvAmt
, sum(IsNull(payments.Amount,0)) PayAmount
, Sum(item.InvItemTotal) InvAmt - sum(IsNull(payments.Amount,0)) as Balance
from SalesInvItems item
left join payments -- you didn't define this
on item.InvRef = payments.InvRef
group by item.InvRef
, item.CustomerName
, item.InvDate
, item.InvDueDate
Select item.InvRef
, item.CustomerName
, item.InvDate
, item.InvDueDate
, Sum(item.InvItemTotal) InvAmt
from SalesInvItems item
left join Statement
on item.InvRef = Statement.Reference
group by item.InvRef
, item.CustomerName
, item.InvDate
, item.InvDueDate

Is it possible to create an SQL query that displays results like this?

Background
I have a database that hold records of all assets in an office. Each asset have a condition, a category name and an age.
A ConditionID can be;
In use
Spare
In Circulation
CategoryID are;
Phone
PC
Laptop
and Age is just a field called AquiredDate which holds records like;
2009-04-24 15:07:51.257
Example
I've created an example of the inputs of the query to explain better what I need if possible.
NB.
Inputs are in Orange in the above example.
I've split the example into two separate queries.
Count would be the output
Question
Is this type of query and result set possible using SQL alone? And if so where do I start? Would it be easier to use Ms Excel also?
Yes it is possible, for your orange fields you can just e.g.
where CategoryID ='Phone' and ConditionID in ('In use', 'In Circulation')
For the yellow one you could do a datediff of days of accuired date to now and divide it by 365 and floor that value, to get the last one (6+ years category) you need to take the minimum of 5 and the calculated value so you get 0 for all between 0-1 year old etc. until 5 which has everything above 6 years.
When you group by that calculated column and select the additional the count you get what you desire.

how to know how many times its a value in the databes? and for all values?

This can be aplied to tags, to coments, ...
My question its to obtain for example, top 20 repetitions for an atribute in a table..
I mean, i know i can ask for a selected atribute with the mysql_num_rows, but how do i do it to know all of them?
For example,
Most popular colors:
Red -100000
blue -5000
white -200
and so on...
if anyone can give me a clue.. thanks!
SELECT `name`, count(*) as `count` FROM `colors`
GROUP BY `name`
ORDER BY `count` DESC
You want to do this computation on the database, not in your application. Usually, a query of the following form should be fine:
SELECT color_id, COUNT(product_id) AS number
FROM products
GROUP BY color_id
ORDER BY number DESC
LIMIT 20
It will be faster this way, as only the value-count data will be sent from the database to the application. Also, if you have indices set up correctly (on color_id, for instance), thighs will be smoother.

Resources