SQL Count from Two Tables with Inner Join from Third Table - php

My database has two similar tables with different names. One of the columns contained in both tables is called "zips", which contains a zip code.
I have a different table (US zip code table) where each entry contains a county name, county ID, state, state ID, and zip code.
I need a query that will tell me how many entries in the first two tables match a given county ID, and will group the results by county.
That is, lets say table A has 4 entries for zip code '30017', and table B has 1 entry for '30017'. In the US zip code table, '30017' corresponds to the county name "Gwinnett" and the county ID '839'. When I run the query the desired result is:
Gwinnett 5
Here is the latest query I've tried. I have no idea what numbers it's returning. It's definitely not what I'm expecting, as I've tried the individual component queries to test the results.
SELECT b.County, COUNT(*) as Calls FROM (aLeads a, pLeads p)
INNER JOIN zipCodes b ON a.zip = b.ZipCode
WHERE b.countyID IN (2897, 2146, 839)
AND a.callDate BETWEEN '2013-10-01' AND '2013-11-30'
GROUP BY b.County
Any ideas?

Try starting with the zipcode table, and joining it with aLeads and pLeads:
SELECT b.County, COUNT(*) as Calls
FROM zipCodes b
INNER JOIN aLeads a ON a.zip = b.ZipCode
INNER JOIN pLeads p ON p.zip = b.ZipCode
WHERE b.countyID IN (2897, 2146, 839)
GROUP BY b.County

Related

Retrieving management hierarchy report from db

I need to prepare report that returns for each of our employee complete list of their higher ups.
I have two mariadb tables: employee and position
employee:
id, name, first_boss_id, position_id,
position:
id, position_name
Employee table contains all employees from juniors to top managers, but every entry contains only name of employee and his closest boss in hierarchy. How can I get all of the managers above him? I've got this so far:
SELECT e.id, e.name, p.position_name, b.name,
FROM employee e
LEFT JOIN employee b ON e.firts_boss_id = b.id
LEFT JOIN position p ON e.position_id = p.id
It returns id, name of employee, his carrier position and name of his closest manager/boss. How can I get names of the rest of higher management for this employee? Is it better to use SQL query or write some PHP script to create that report from data I get from query above?
Either way I could really use some pointers how to get it done. Thank you!

Getting two values from same Joined table

I have two tables:
procedures
countries
Table procedures has two columns
destination_country_iso
origin_country_iso
Table countries
iso
name
Im trying to join up the two tables in order to get both destination an origin country name from countries table.
SELECT *
FROM draft_procedures AS drp
LEFT JOIN countries AS c1 ON drp.destination_country_iso = c1.iso
LEFT JOIN countries AS c2 ON drp.origin_country_iso = c2.iso
The SQL result display proper result, but I now have two duplicate columns "name" and Im unable to retrieve them with the php code:
$destination_country=$row['c1.name'];
access it like this
SELECT drp.*,c1.name as c1name,c2.name as c2name
then
$row['c1name'] $row['c2name']

How do I generate several reports from one MySQL query?

I need to report the number of records that match each of several criteria. For example, how many customers live in each state. I know I can accomplish this through a series of MySQL SELECT statements, but that seems cumbersome and produces a ton of (unnecessary?) MySQL calls.
Can you tell me a better method to use? Can I query the database with one SELECT statement and then use PHP to filter the results to variables?
I'd suggest creating a view for this task just to hide the complexity of the query. Also, in the event that your table schema changes, it is likely that you are still going to want to retrieve this same information from the database. You'd be able to change the view in one place, instead of having to change the queries in, possibly, multiple places to satisfy your schema changes.
I'll just show you the queries, though, since you'd need to know how to do that to create a view anyways.
Sticking with your example of customers living in each state, let's pretend you also want statistics on how many customers share the same last name.
I've setup a mock structure of what your database might be like at this SqlFiddle.
Customers with Same LastName
The following query might be used to get the number of customers with the same last name:
SELECT
LastName AS "Value",
COUNT(*) AS "Count"
FROM Customers
GROUP BY
LastName;
Customers in Same State
Similarly, the customers in the same state might be retrieved with a query as follows:
SELECT
S.Name AS "Value",
COUNT(*) AS "Count"
FROM Customers AS C
INNER JOIN CustomerAddresses AS CA ON C.Id = CA.CustomerId
INNER JOIN Addresses AS A ON CA.AddressId = A.Id
INNER JOIN States AS S ON A.State = S.Id
GROUP BY
A.State;
Getting Your Desired Format
The format that you want is an aggregation of these two queries. You want both returned as a single result set. So, let's workout a schema for the returned table:
ResultType - This will hold a value that corresponds to the type of result. i.e. "State"
Value - This will hold the value of the aggregated column. i.e. "Florida"
Count - This will hold the total number of records that match the aggregated column.
So, now that we have a format, let's create a query that uses our two queries from above, and puts them into this format.
First, I add a new field to each of the above queries: ResultType
For example:
"LastName" AS "ResultType"
Now, I combine my queries into a single query using the UNION ALL statement:
SELECT * FROM (
/* LastName query */
SELECT
"LastName" AS "ResultType",
LastName AS "Value",
COUNT(*) AS "Count"
FROM Customers
GROUP BY
LastName
UNION ALL
/* States query */
SELECT
"State" AS "ResultType",
S.Name AS "Value",
COUNT(*) AS "Count"
FROM Customers AS C
INNER JOIN CustomerAddresses AS CA ON C.Id = CA.CustomerId
INNER JOIN Addresses AS A ON CA.AddressId = A.Id
INNER JOIN States AS S ON A.State = S.Id
GROUP BY
A.State
) AS A
In my SqlFiddle above, this produces an output like:
RESULTTYPE VALUE COUNT
=================================
LastName Jetson 1
LastName Johnson 2
LastName Milton 1
State Florida 2
State Georgia 1
State Utah 1
As you can see, this could get quite complex, so you might consider looking into placing this into a view. Then, you'd be able to query your view, as if it was the table above (ResultType, Value, and Count). That would also allow you to filter on it.
create select query make number of aliens of table and make your related columns aliens which is you want to use.
lest see sample example
SELECT a.id AS id
FROM Table1 AS a
WHERE ...
UNION ALL
SELECT b.name AS name
FROM Table2 AS b
WHERE ...
ORDER BY (a or b) ...

data show from 4 table mysql

How to show the common data from all table on base of vendorID where vendorID is unique key in my vendor table. and i use this as an foriegn key for all other(cost table, hour table,employee table, temporary table and ) table.
This is my Cost table struructre
This is my Hour table structure
This is my Temporarytable structure
This is my Employee table
This is my Final table vendor there are vendorID is unique Key
And i have use the following query but it is showing the different data.
SELECT * FROM cw_employee_csv as emp
inner join cw_cost_hour as cost on cost.vendorid=emp.vendorid
inner join cw_temp_employee as temp on cost.vendorid=temp.vendorid
inner join cw_hour_company as hour on temp.vendorid=hour.vendorid
inner join cw_vendor as vendor on temp.vendorid=vendor.vendorid
where vendor.companyid=1 ORDER BY hour.timeFrom ASC
If I understand, try this:
In your query in the field list explicit fields you want to show, for example:
SELECT
emp.assignmentid, cost.bill_type
FROM
cw_employee_csv AS emp
INNER JOIN
cw_cost_hour AS cost ON cost.vendorid = emp.vendorid
INNER JOIN
cw_temp_employee AS temp ON cost.vendorid = temp.vendorid
INNER JOIN
cw_hour_company AS hour ON temp.vendorid = hour.vendorid
INNER JOIN
cw_vendor AS vendor ON temp.vendorid = vendor.vendorid
WHERE
vendor.companyid = 1
ORDER BY
hour.timeFrom ASC
If the cardinality of tables is different and you want to show only one row per vendor, you must write a main query with cw_vendor and use some subquery to retrieve additional information by other table. Obviously, about parent table of your vendor table you can use INNER JOIN information without use subqueries.
EDIT AFTER COMMENT:
You start by this query (after chat discussion):
I extract an aggregate by company (I suppose to summarize your cost by vendor, if you want to apply another formula, it's the same algorithm)
select
sum(t.vendor_cost), t.companyid
from
(select
vendor.companyid as companyid, vendor.id as vendorid,
(select SUM(c.cost)
from cw_cost_hoyr c
where c.vendorid = vendor.id) as vendor_cost
from
cw_vendor vendor) as t
group by
t.companyid
Now we add other information but I must understand what do you want exactly with their relations

Joining multiple (4) tables in MYSQL

I have four tables I want to join and get data from. The tables look something like...
Employees (EmployeeID, GroupID[fk], EmployeeName, PhoneNum)
Positions (PositionID, PositionName)
EmployeePositions (EployeePositionID, EmployeeID[fk], PositionID[fk])
EmployeeGroup (GroupID, GroupName)
[fk] = foreign key
I want to create a query that will return all the information about an employee(given by EmployeeID). I want a query that will return the given employees Name, position(s), and group in one row.
I think it needs to involve joins, but I am not sure how to format the queries. MYSQL's manual is technical beyond my comprehension. I would be very grateful for any help.
It seems you have trouble with SQL, in general, rather than with mySQL in particular. The documentation of mySQL provides details about the various SQL expressions, but generally assume some familiarity with SQL. To get a quick start on SQL you may consider this W3schools.com primer.
The query you need is the following.
SELECT EmployeeName, PositionName, GroupName
FROM Employees E
LEFT JOIN EmployeePositions EP ON EP.EmployeeID = E.EmployeeID
LEFT JOIN Positions P ON P.PositionID = EP.PositionId
LEFT JOIN EmployeeGroup EG ON EG.GroupId = E.GroupId
WHERE E.EmployeeId = some_value
A few things to note:
The 'LEFT' in 'LEFT JOIN' will result in producing NULL in lieu of PositionName or GroupName when the corresponding tables do not have a value for the given FK. (Should only happen if the data is broken, say if for example some employees have GroupId 123 but somehow this groupid was deleted from the EmployeeGroup table.
The query returns one line per employee (1). You could use an alternative search criteria, for example WHERE EmployeeName = 'SMITH', and get a listing of all employees with that name. Indeed without a WHERE clause, you'd get a list of all employees found in Employees table.
(1) that is assuming that each employee can only have one position. If somehow some employees have more than one position (i.e. multiple rows in EmployeePositions for a given EmployeeID), you'd get several rows per employee, the Name and Group being repeated and a distinct PostionName.
Edit:
If a given employee can have multiple positions, you can use the query suggested by Tor Valamo, which uses a GROUP BY construct, with GROUP_CONCAT() to pivot all the possible positions in one single field value in the returned row.
SELECT e.EmployeeID, e.EmployeeName, e.PhoneNum,
g.GroupName, GROUP_CONCAT(p.PositionName) AS Positions
FROM Employees e
LEFT JOIN EmployeeGroup g ON g.GroupID = e.GroupID
LEFT JOIN EmployeePositions ep ON ep.EmployeeID = e.EmployeeID
LEFT JOIN Positions p ON p.PositionID = ep.PositionID
WHERE e.EmployeeID = 1
GROUP BY e.EmployeeID
Returns positions in a comma separated string on one row.

Categories