I have information from 2 different SQL Server 2008 databases.
DB1 has the following related tables with Employee information
Employee
empDepartment
empLocation
DB2 has a table Refunds with refund requests.
Since they are on different Databases, I'm planning on using PowerPivot to create cross DB pivot tables to be able to show things like Refund requests by department, etc.
I'm able to bring in all the data with no issues EXCEPT for the Employee table. I don't have access to the source data. I'm pulling from a data warehouse of sorts, and there happen to be duplicate employee IDs in the data (great!). I've tried SELECT DISTINCT queries but the entire row isn't duplicated, in most cases it's just a bad Employee ID.
The other issue, is that only a small portion of employees (1-2K) submit refund requests on behalf of customers, so it seems silly to pull in the entire employee table (200k records).
So I got the crazy idea that I could dynamically pull the Employee table using the employeeID column in the Refunds table. But I can't seem to find a place to use existing PowerPivot tables in a separate PowerPivot query.
Here is the SQL for how I'm currently pulling the employee information
SELECT DISTINCT
emp.NTLogin as 'Employee_NTLogin'
, emp.LastName + ', ' + emp.FirstName as Emp_FullName
, emp.PositionCode as 'Position'
, emp.DepartmentID as 'Department'
, emp.LocationID as 'Location'
, emp.HireDate as 'Employee_HireDate'
, emp.EndDate as 'Employee_EndDate'
FROM dbo.Employee emp
WHERE
emp.EndDate IS NULL
OR emp.EndDate BETWEEN '04/01/2014 00:00:00' AND GETDATE()
ORDER BY
emp.LastName + ', ' + emp.FirstName
(the WHERE clause is filtering out employees that were current employees from 4/1 to today)
Not a lot of info about the actual pivot table you are using but here is an example of how to grab the data, you'll have to edit to match your tables.
ActiveSheet.PivotTables(1).PivotFields("Employee").PivotItems("ID").DataRange.Select
You'll probably want to place that data into an array and then pass that to your sql query. Not a complete answer, but hopefully it will get you on the path.
Related
I have a query i have been working on trying to get a specific set of data, join the comments in duplicate phone numbers of said data, then join separate tables based on a common field "entry_id" which also happens to be the number on the end of the word custom_ to pull up that table.
table named list and tables containing the values i want to join is custom_entry_id (with entry_id being a field in list in which i need the values of each record to replace the words in order to pull up that specific table) i need entry_id from the beginning part of my query to stick onto the end of the word custom for every value my search returns to get the fields from that custom table designated for that record. so it will have to do some sort of loop i guess? sorry like i said I am at a loss at this point
this is where i am so far:
SELECT * ,
group_concat(comments SEPARATOR '\r\n\r\n') AS comments_combined
FROM list WHERE `status` IN ("SALEA","SALE")
GROUP BY phone_number
//entry_id is included in the * as well as status
// group concat combines the comments if numbers are same
i have also experimented on test data with doing a full outer join which doesnt really exist. i feel if you can solve the other part for me i can do the joining of the data with a query similar to this.
SELECT * FROM test
LEFT JOIN custom_sally ON test.num = custom_sally.num
UNION
SELECT * FROM test
RIGHT JOIN custom_sally ON test.num = custom_sally.num
i would like all of this to appear with every field from my list table in addition to all the fields in the custom_'entry_id' tables for each specific record. I am ok with values being null for records that have different custom fields. so if record 1 has custom fields after the join of hats and trousers and record 2 has socks and shoes i realize that socks and shoes for record 1 will be null and hats and trousers for record 2 will be null.
i am doing all this in phpmyadmin under the SQL tab.
if that is a mistake please advise as well. i am using it because ive only been working with SQl for a few months. from what i read its the rookie tool.
i might be going about this all wrong if so please advise
an example
i query list with my query i get 20,000 rows with columns like status, phone_number, comments, entry_id, name, address, so on.
now i want to join this query with custom fields in another table.
the problem is the custom tables' names are all linked to the entry_id.
so if entry_id is 777 then the custom table fields are custom_777
my database has over 100 custom tables with specials fields for each record depending on its entry_id.
when i query the records I don't know how to join the custom fields that are entry_id specific to the rest of my data.i will pull up some tables and data for a better example
this is the list table:
this is the custom_"entry_id"
Full Outer Join in MySQL
for info on full outer joins.
I have a MySQL statement that I want to use that will display the data in two different tables, but not have any duplicated data.
SELECT Customer.firstName, Customer.lastName, Purchase.productName, Purchase.productPrice
FROM Purchase
INNER JOIN Customer
This is currently the MySQL I am using and it does work, but it loads duplicated data which I do not want. I have looked around but not seeing a simple solution. Sorry in advance if it is a simple solution, been working for awhile and brain isn't really working.
You have to bind those tables via related columns.
Let's assume primary column of table Customer is named ID and customer ID is being held in a column named customerID in table Purchase:
SELECT Customer.firstName, Customer.lastName, Purchase.productName, Purchase.productPrice
FROM Purchase
INNER JOIN Customer
ON Custormer.ID=Purchase.customerID
update employee as a
set a.sup_role=(
select b.job_role from employee as b
where b.supervisorid=a.employeeid
group by b.job_role
order by count(b.job_role) desc
limit 1
)
where a.job_role='MAN1';
OK I have a table of all of our employees - around 100K.
All of our users have job roles that I built based on their employee.job_title. So based on 4K+ job_titles I knock that down to about 40 job_roles. This is so we can assign things in our CMS based on employee.job_roles. This has been working good but the problem is with the managers. The managers get some generic corporate job_title that we role into a generic job_role.
What you see above is code that I use to kind of do what I need to do - find out what job_role a supervisor based on what "most of their employees do". This outputs the correct sup_role but there are several things wrong with my code:
based on my syntax it won't let me update the employee table directly. I have have to update an employee "helper" table and fill in later.
So it is parsing through for the job_role "MAN1". First I don't want to update this to add new manager job roles. Also this doesn't account for my company doing ad hoc things like a manager just have a regular job title or different NULL fields.
And then the last part is that this code is taking 6 minutes to go through. Luckily I run this as a batch job but I am afraid it might cause crashes.
So I have the following table -
employee
with applicable fields
employeeid
supervisorid
job_title
job_role
sup_role
So below is my last attempt. It just runs and never outputs anything. I am wondering if I need to create a helper table to grab the DISTINCT supervisorid's since one employee could be many people's supervisor.
update employee as a
set a.sup_role=(
select b.job_role from employee as b
where b.supervisorid=a.employeeid
group by b.job_role
order by count(b.job_role) desc
limit 1
)
WHERE a.uid IN (select DISTINCT employee.supervisorid
from employee
where employee.supervisorid is not null
);
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 am working on extracting financial information from a couple of tables and summarizing it into another table. What I want is to select several account items from a balancesheet table by accountID, summing the items and then saving the result into another table. I need to do this for several clients. I have worked out part of the problem in this bit of code:
;with
T1 AS (
SELECT CompanyID, QEndDate, Qtr, [50], [76] FROM (
SELECT CompanyID, ItemID, CAST(Amount AS DECIMAL(18,4)) AS Amount, QEndDate, Qtr from BalanceSheet
WHERE CompanyID = 2335 AND (ItemID = 50 OR ItemID = 76) AND Amount <> '-'
AND QA = 'Q' )as s
PIVOT (MAX(Amount) FOR ItemID IN ([50], [76])) AS P
)
UPDATE Funds SET Funds.EV = (#mCap - ([50] + [76])) / #EB
FROM T1
INNER JOIN Funds ON T1.CompanyID = Funds.CompanyID
The above works fine for one Company, but I need to do several at a time.
A little added info:
The Balancesheet table contains all information as VARCHAR, hence the <> '-', which some companies (but not all) use to indicate Not Applicable as opposed to zero.
The 50 and 76 are item numbers from the Accounts table and indicate which account the amount belongs to.
I am picking up the amounts and items from the balancesheet table and assembling them on one line so that I can then access the items, perform some math and generate a result to be stored in the Funds table. I hope that all makes sense.
So how can I turn this into something that can perform the operations for as many customers as I need.
Thanks, and also special thanks to all the good folks who contributed ideas and code that allowed me to get this far.
What's stopping this for working over many companies, as is?
You are limiting the company by selection "WHERE CompanyID = 2335"; just broaden the scope of the data within the pivot. If this is unhelpful, then not sure I understand where the limitation is.