I have a table that in one column has security companies in it, another column has the id of the parent company, and the last column has that security company's market value.
I am trying to calculate the parent company's market value by adding together the market values of the security companies with the same parent id, how do I accomplish this?
The table is called security and I want the new column to be called ParentSecMktValue.
I have tried using SELECT statements:
SELECT security.Parent_id, security.SecMktValue
FROM security
ORDER BY Parent_id ASC;
This produces a table of the parent id's and their market values but I am unsure how to combine the data from the different rows.
SELECT s.Parent_id, SUM(s.market_value) AS ParentSecMktValue
FROM security s
GROUP BY s.Parent_id
;
You can get the sum by using group by on parent_id and using sum function on market value
SELECT security.parent_id, SUM(security.SecMktValue)
FROM security GROUP BY parent_id
ORDER BY Parent_id ASC;
Related
I am trying to retrieve the the first row among the duplicate row, THE FIRST OCCURED ***
--Table--
Order_No Product User
1 Book Student
2 Book Student
3 Book Student
I want to get the Order_No of the first duplicate row in JAVA, I have used DISTINCT and DISTINCT TOP 1 etc but nothing worked, NEED HELP
SELECT min(order_no), product, user
FROM 'table'
GROUP BY user, product
This is basic SQL?
SELECT min(order_no), product, user FROM table GROUP BY product, user
See also more information on GROUP BY
All fields not part of your group by must have some sort of way to determine which to pick of the n potentially different values. min() will pick the lowest value (even with strings and dates) while max() will pick the highest. You can also use First() and Last() to grab the value according to when they show up.
Supposing you had other values to pick from, you might see something like:
SELECT min(order_no), product, user, min(creation_date),
sum(quantity), first(billing_address)
FROM orders GROUP BY product, user
SELECT t.*
FROM table t
WHERE NOT EXISTS ( SELECT a
FROM table t2
WHERE t2.Product = t.Product
AND t2.User = t.User
AND t2.Order_No < t.Order_No
)
I am working on an employee management/reward system and need to be able to show a single "transaction history" page that shows in chronological order the different events that the employee has experienced in one list. (Sort of like how in facebook you can goto your history/action section and see a chronological list of all the stuff that you have done and affects you, even though they are unrelated to eachother and just have you as a common user)
I have different tables for the different events, each table has an employee_id key and an "occured" timestamp, some table examples:
bonuses
customers
raise
complaints
feedback
So whenever an event occurs (ie a new customer is assigned to the employee, or the employee gets a complaint or raise) a new row is added to the appropriate table with the employee ID it affects and a timestamp of when it occured.
I need a single query to pull all records (upto 50 for example) that include the employee and return a history view of that employee. The field names are different in each table (ie the bonus includes an amount with a note, the customer includes customer info etc).
I need the output to be a summary view using column names such as:
event_type = (new customer, bonus, feedback etc)
date
title (a brief worded title of the type of event, specified in sql based on the table its referencing)
description (verbiage about the action, such as if its event_type bonus display the bonus amount here, if its a complain show the first 50 characters of the complaint message or the ID of the user that filed the complaint from the complaints table. All done in SQL using if statements and building the value of this field output based on which table it comes from. Such as if its from the customers table IF current_table=customers description='A customer was assigned to you by'.customers.assigner_id).
Ideally,
Is there any way to do this?
Another option I have considered, is I could do 5-6 different queries pulling the records each from their own table, then use a mysql command to "mesh/interleave" the results from all the queries into one list by chronological order. That would be acceptable too
You could use a UNION query to merge all the information together and use the ORDER BY clause to order the actions chronologically. Each query must have the same number of fields. Your ORDER BY clause should be last.
The examples below assume you have a field called customer_name in the customers table and bonus_amount in the bonuses table.
It would look something like this:
SELECT 'New Customer' as event_type, date,
'New customer was assigned' as title,
CONCAT('New Customer: ', customer_name, ' was assigned') as description
FROM customers
WHERE employee_id = 1
UNION
SELECT 'Bonus' as event_type, date,
'Received a bonue' as title,
CONCAT('Received a bonus of $', FORMAT(bonus_amount, 2), '.') as description
FROM bonuses
WHERE employee_id = 1
UNION
...
ORDER BY date DESC;
I have a table Mbr that contains 3 fields, GroupType, LeaderID, and MemberID. Basically, all the members in an organization are divided up into these groups, identified by their leader's unique ID (LeaderID). Each member record also has their own MemberID, and the leaders themselves have a unique MemberID as well. The GroupType just designates whether the group a member is in which is considered a Large, Small, or Individual group.
I need to find out how many groups of each GroupType contain a certain number of members.
For example:
How many Large groups contain 6 members, 7 members, 8 members, 9 and so on.
How many Small Groups contain 2 members, 3 members, 4 members and 5 members
How many Individual groups there are.
Is it possible make a query to get a Count of the unique MemberID's for each group, and then get a COUNT of how many LeaderID's have a certain number of members associated to them?
Note: Since you are not specifying which DBMS you are using, I tried to do a basic query. In SQLServer or Oracle this can be much more elegant.
I'm assuming that a given Member can be Leader leader of only one Group if that is correct,
Question #1:
SELECT GroupType, NumberOfMembers, COUNT(LeaderID) AS NumberOfGroups
FROM (
SELECT GroupType, LeaderID, COUNT(*) AS NumberOfMembers
FROM MyTable
GROUP BY GroupType, LeaderID
) AS InnerGrouping
GROUP BY GroupType, NumberOfMembers
ORDER BY GroupType, NumberOfMembers
Question #2:
SELECT UniqueMemberIDPerGroup, COUNT(LeaderID) AS NumberOfLeaderID
FROM (
SELECT LeaderID, COUNT(DISTINCT MemberID) AS UniqueMemberIDPerGroup
FROM MyTable
GROUP BY LeaderID
) AS InnerGrouping
GROUP BY UniqueMemberIDPerGroup
I'm sure you can write some complex query with several subqueries to create a query to give you what you want, but I personally like more straightforward methods. In this case, it would be using some temp tables to store intermediate values. I would first group by several columns (that you are going to use as criterias) with count being the value for the query. I would then store these into a temp table and finally create a query to utilize the temp table to give you the results that you are looking for.
I have a table with a bunch of orders... one of the columns is order_status. The data in that column ranges from 1 to 5. Each number relates to a name, which is stored in another table that relates that number to the respective name.
SELECT order_id , order_status FROM tablename1
The above would just return the numbers 1,2,3,4,5 for order status. How can i query within the query on the fly to replace these numbers with their respective names.
Also, what's the term used to describe this. I'd Google it if i knew what the appropriate term was.
Each number relates to a name, which is stored in another table that
relates that number to the respective name.
JOIN it with the other table:
SELECT
t.order_id,
s.StatusName
FROM tablename1 AS t
INNER JOIN the statusesTable AS s ON t.order_status = s.status_id;
I'm sure there are a ton of ways to do this, but right now I'm struggling to find the way that will work properly given the data.
I basically have a table containing duplicates which have additional fields tied to them and source details that take priority over others. So basically I added a "priority" field to my table which I then updated based on source priority. I now need to select the distinct records to populate my "unique" records table (which I'll then apply unique key constraint to prevent this from happening again on the field required!)....
So I have basically, something like this:
Select phone, carrier, src, priority
from dbo.mytable
So basically I need to pull distinct on phone in order of priority (1,2,3,4, etc), and basically pull the rest of the other data along with it and still keep UNIQUE on phone.
I've tried a few things using sub-select from the same table with min(priority) value, but outcome still doesn't seem to make sense. Any help would be greatly appreciated. Thanks!
EDIT I need to dedupe from the same table, but I can populate a new table with the uniques if needed based on my select statement to pull the uniques. This is in MSSQL, but figured anyone with SQL knowledge could answer.
For example, let's say I have the following rows:
5556667777, ATT, source1, 1
5556667777, ATT, source2, 2
5556667777, ATT, source3, 3
I need to pull uniques based on priority 1 first..... the problem is, I need to remove any all other dupes from the table based on the priority order without ending up with the same phone number twice again. Make sense?
So you're saying the combination (phone, priority) is unique in the existing table, and you want to select the rows for which the priority is smallest?
SELECT mytable.phone, mytable.carrier, mytable.src
FROM mytable
INNER JOIN (
SELECT phone, MIN(priority) AS minpriority
FROM mytable
GROUP BY phone
) AS minphone
ON mytable.phone = minphone.phone
AND mytable.priority = minphone.minpriority