I have two tables. One tracks Part Shipments and the other tracks System shipments.
I am trying to count the customer contacts in each table with the result showing me the total customer contacts for both parts and systems combined.
I am trying to use Union and I would guess from my results I am doing this all wrong. My results end up with two entries for customers. Cust A will have a total of 9 and then another entry of 1. So I am guess there is no merge of the customer contacts and it is just creating a union of both results.
The Code I am using.
SELECT Count(part_shipment.Customer_Station_ID) AS Contact,
part_shipment.Customer_Station_ID AS Customer
FROM part_shipment
GROUP BY part_shipment.Customer_Station_ID
UNION
SELECT Count(system_shipments.Customer_Station_ID) AS Contact,
system_shipments.Customer_Station_ID AS Customer
FROM system_shipments
GROUP BY system_shipments.Customer_Station_ID
ORDER BY Contact DESC
You can't do it like that. The Union just take rows from first query and rows from second query, and "display" them ones after anothers.
UNION requires the creation of derived tables (tables created from a query).
SELECT *
FROM (
SELECT col1, col2
FROM table
) UNION (
SELECT col1, col2
FROM otherTable
)
I also don't think you can use GROUP BY inside the selects that make up the UNION (it's been a while since I used it so I don't remember for sure)
Do you have tried to use a GROUP BY and SUM from the results of UNION query?
Related
I have two separate tables on MySQL, and I want to make a query where I select * from both of them and I want to order them by id (or date). The problem is the id's will conflict, since there will be two articles with the same id (one from each table).
Is there a way where I can display all the articles of each table in one single query?
Edit:
They don't have the same number of columns. However, I will be choosing the same columns of each of them. So I'd be selecting "id, map, title, summary, image, date, publish" from both table1 and table2. (because both of the tables have those exact same columns).
Then I want to display on a single web page all the articles from both table1 and table2. In the exact same grid.
Is this even possible or do I need to merge both tables in MySQL?
If the 2 tables have the same number of columns and the data types of the corresponding columns are the same, then you can use UNION ALL:
SELECT * FROM table1
UNION ALL
SELECT * FROM table2
ORDER BY id
If you also want to distinguish the rows so you know from which table they originate, you can create a dummy 1st column for each of them like this:
SELECT '1' fromtable, * FROM table1
UNION ALL
SELECT '2' fromtable, * FROM table2
ORDER BY id
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) ...
SELECT a.delivery_date,
a.delivery_hour,
a.price as EX-ANTE,
FROM mms_realtime_dispatch_prices_report a
UNION ALL
SELECT b.delivery_date,
b.delivery_hour,
b.price as EX-POST,
FROM mms_realtime_dispatch_prices_report b
UNION ALL
SELECT c.region,
c.dem_rtdel,
c.date,
FROM pub_demand_lwap c;
UNION ALL
SELECT region,
report,
hour,
SUM(q1,q2,q3,q4,q5,q6,q7,q8,q9,q10,q11)
FROM pub_markets_bids_and_offers
WHERE delivery date=03/16/2011
GROUP BY hour
help! need to combine this four table into one new table no duplicate data
Can you help me in combining this four tables into one table. this is the first time i encounter this. I really need a help :(
In SQL server union works only if there is same number and type of columns return by query.
You need to get your Union query right 1st I can see so many things wrong with Query At the moment,
Your number of columns retunred by each select arent same, Last query is returning 4 columns and other 3,
You are Aliasing Columns in 2nd query, it will not have any effect as Only the Column Names from very first select statement are visible in the result set.
Guessing from the Column names you have Different Data Types that
you are trying to UNION. Datatypes Returned from all selects that you are using in UNION should return the same datatypes e.g
SELECT Column1_DataType1, Column2_DataType2, Column3_DataType3 FROM Table_Name1
UNION ALL
SELECT Column1_DataType1, Column2_DataType2, Column3_DataType3 FROM Table_Name2
UNION ALL
SELECT Column1_DataType1, Column2_DataType2, Column3_DataType3 FROM Table_Name3
and so on....
Once you have met all these condition then you can do something like this to eliminate duplicate rows from you result set
;with CTE
AS
(
SELECT ID_Column, rn = ROW_NUMBER() OVER (PARTITION BY Column1, Column2, Column3... ORDER BY ID ASC)
FROM ( -- All of your UNION ALL Statements Can go here --)q
)
DELETE FROM CTE
WHERE rn = 1
I know I can do joins but its not exactly what I want.
I'm making a live chat system that has 2 tables mainly: the main chat table (call it table a), and then a mod table (call this one table b). If a user gets suspended, messages reach over 100 for that channel, or they are over 1 week, the messages get moved from the main chat table to the mod table.
I store the ID of the chat messages as ID(primary) on the main chat table and as chatID on the mod table.
What I'm doing is making a separate page for my Mods and I want to be able to combine the two tables into 1 area but I want them to be ordered by their respective tables.
So lets say we had the following:
Main table ID's: 1,2,4
Mod table ID: 3
I want my results to show up 1,2,3,4 no matter which table the ID is in.
Any help is greatly appreciated!
Edit: I got the answer and this is what I used to do so:
SELECT ab.* FROM
((SELECT ID as table_id FROM a
WHERE roomID = 'newUsers' ORDER BY ID ASC)
UNION ALL
(SELECT chatID as table_id FROM b
WHERE roomID = 'newUsers' ORDER BY chatID ASC)) ab
ORDER BY ab.table_id
Use a UNION in a subselect.
SELECT ab.* FROM (
SELECT 1 as table_id, * FROM a
UNION ALL
SELECT 2 as table_id, * FROM b
) ab
ORDER BY ab.id
If you want the result of table A to appear before table B, change the query to:
SELECT ab.* FROM (
SELECT 1 as table_id, * FROM a
UNION ALL
SELECT 2 as table_id, * FROM b
) ab
ORDER BY ab.table_id, ab.id
Some background
UNION ALL will merge two tables resultsets into one resultset.
UNION will do the same but will eliminate duplicate rows.
This takes time and slows things down, so if you know there will be no duplicate records (or you don't care about dups) use UNION ALL.
See also: http://dev.mysql.com/doc/refman/5.5/en/union.html
I have two tables which are used to store details of different types of events.
The tables are almost identical, with fields such as date, duration etc. I'm trying to perform a join on the two tables and sort them by the mutual field 'date'.
I know it would be simpler to simply add a 'type' field to a single table and store it all in a single place, unfortunately the nature of the cms I am using does not allow this.
Is there a way to perform this simply? The following query returns no results.
$sql = "SELECT * FROM Events_One a, Events_Two b WHERE a.Date > now() OR b.Date > now() ORDER BY Date ASC LIMIT ".$limit;
You should look at UNION statement. It does exactly what you need.
SELECT columns FROM t1
UNION
SELECT columns FROM t2
gives you one set, which you can later filter or sort by whatever you want.
If you have a table for each event type, with identical fields for each one, I'd say that you should reconsider your design. That's breaking normalization rules. It's a poor design because it forces you to add another table every time a new event comes along. It's better if you can add a new event by adding data, like a new type value, to an existing table.
If you want to join two similar tables You can use Union or union all
Union:its Like a join Command.When using the union all the selected columns need to be of the same datatype.Only distinct values are selected.
Union All :it almost like union.There is no distinct operation so it will take all the values.
select * FROM Events_One a WHERE a.Date > now()
union
select * FROM Events_Two b WHERE b.Date > now()