I'm currently learning how to use MySQL
in queries and I have a dilemma.
Currently, I have 2 queries that fetch data from multiple tables. Both queries contain the same number of column fields and field names.
For simplicity, the output of the queries looks something like this:
QueryOne:
FieldOne| FieldTwo | FieldThree | CountOne | CountTwo | CountThree
data1 | data11 | data111 | 3 | 0 | 0
data2 | data22 | data222 | 0 | 1 | 0
data3 | data33 | data333 | 0 | 0 | 2
data4 | data44 | data444 | 0 | 4 | 0
data5 | data55 | data444 | 0 | 0 | 1
QueryTwo:
FieldOne| FieldTwo | FieldThree | CountOne | CountTwo | CountThree
data1 | data11 | data111 | 1 | 0 | 0
data1 | data11 | data111 | 0 | 0 | 2
data6 | data66 | data666 | 0 | 5 | 0
Both queries contain the same data for FieldOne-FieldThree, but may contain different values for CountOne-CountThree.
There will never be an instance where the data will contain values in all 3 fields CountOne, CountTwo, CountThree
, but only in ONE of those 3 fields.
What I'm trying to do is create a separate UNION QUERY
that has the following output:
FieldOne| FieldTwo | FieldThree | CountOne | CountTwo | CountThree
data1 | data11 | data111 | 4 | 0 | 0
data1 | data11 | data111 | 0 | 0 | 2
data2 | data22 | data222 | 0 | 1 | 0
data3 | data33 | data333 | 0 | 0 | 2
data4 | data44 | data444 | 0 | 4 | 0
data5 | data55 | data444 | 0 | 0 | 1
data6 | data66 | data666 | 0 | 5 | 0
Basically, if there is more than one instance of the same data in FieldOne
, and there is a value in the same CountOne
, CountTwo
, or CountThree
for multiple instance of that same data, I'd like to get the SUM of that field and group that data by FieldOne
.
However, if there is more than one instance of the same data, but it contains a value in a different Count
field, then the query should create a separate record for it, like in the example, data1
contains values in both CountOne
and CountTwo
fields.
I did something like this in SQL View
of Access 2013 with a UNION QUERY
:
SELECT *
FROM [QueryOne]
ORDER BY FieldOne
UNION SELECT *
FROM [QueryTwo]
ORDER BY FieldTwo;
However, with my limited knowledge, I'm stuck on how to incorporate what I want into the above code in one go, instead of creating another separate query.