SQL - Union select issue, results are not described properly - mysql

My Union Select statement works, but the results are on top of each other.
SQL Statement:
SELECT Cust_ID, Cust_FirstName, Cust_LastName
FROM kmsrutge_xoxoxo.Customers
UNION
SELECT Item_Type, Quantity, Total_Amount
FROM kmsrutge_xoxoxo.Invoices
WHERE Total_Amount >= '$5.00'

You should pick (select) at least one column that is the same of both tables, and make a join statement per that column in order to get desired result.

Related

How to use multiple Select statement in MySQL

Lets say i want to select (total Number of Customer from Customer table), as well as (Total Sum of transaction Amount from transaction Table).
I want to list out both result in single query..
select Count(id) from Customer
select Sum(Amount) from Transactions
Please help me to to do.
You can put the two queries in subqueries:
SELECT (SELECT COUNT(*) FROM Customer) AS customers,
(SELECT SUM(amount) FROM Transactions) AS amount
FROM DUAL
You don't need FROM DUAL if you're doing this in MySQL, you may need it in other databases.
You can use join statement to join both table and get data from each table. For join statement refer this link or you can use
SELECT t1.*,t2.* FROM t1,t2

Join two queries with sum of fields as total

I have two queries to sum count all sales of products and other for services in the same database, I am wondering if it is possible to make these 2 queries to just one. Not because they are just queries but also because they sum count. I better show the example here
QUERY 1
SELECT SUM(totalone) AS `total` FROM `sold_products`
WHERE `date`=DATE(NOW()) AND `payment_method`='cash'
QUERY 2
SELECT SUM(totaltwo) AS `total` FROM `sold_services`
WHERE `date`=DATE(NOW()) AND `payment_method`='cash'
Right now I add the two values in my PHP code. It works fine but I just want to know how to do this in just one query. I always query the same payment method and the same date, but just two different tables in the same database.
Any suggestion ?
You can use a UNION and then SUM the values like this:
SELECT SUM(total) FROM (
SELECT totalone AS `total` FROM `sold_products`
WHERE `date`=DATE(NOW()) AND `payment_method`='cash'
UNION ALL
SELECT totaltwo AS `total` FROM `sold_services`
WHERE `date`=DATE(NOW()) AND `payment_method`='cash'
)
Make sure you use UNION ALL instead of UNION, otherwise you will end up discarding any duplicate values in your total column, giving you the wrong sum.
What you want is the UNION operator. You can take the two queries and get them combined as one.
SELECT SUM(total) AS `total` FROM (
SELECT `total` FROM `sold_products`
WHERE `date`='$today' AND `payment_method`='cash'
UNION
SELECT `total` FROM `sold_services`
WHERE `date`='$today' AND `payment_method`='cash')
Here is an article with more information about MySQL UNION:
http://www.mysqltutorial.org/sql-union-mysql.aspx

Mysql Union in different columns

I have the following query
SELECT *
FROM(
(SELECT
MAX(c.start_time) as start_1
FROM
c1 c)
UNION ALL
(SELECT
MAX(cc.created_at) as ccmax
FROM
cc1)
) as t
I'd like to have the result in a table with 2 columns start_1 and cmax instead of the single column I get with all the different results listed.
How should I do it? I ended up in a subselect believing this would have done the job.
For the data to be in two columns you would have to use a sub select.
SELECT
MAX(c1.start_time) as start_1, (SELECT MAX(cc1.created_at) FROM cc1) as ccmax
FROM c1

mysql - how do I get count of counts

I have a table with duplicate skus.
skua
skua
skub
skub
skub
skuc
skuc
skud
SELECT sku, COUNT(1) AS `Count` FROM products GROUP BY sku;
shows me all the skus that have duplicates and the number of duplicates
skua 2
skub 3
skuc 2
skud 1
I am trying to find how many there are with 2 duplicates, 3 duplicates etc.
i.e.
duplicated count
1 1 (skud)
2 2 (skua, and skuc)
3 1 (skub)
and I don't know how to write the sql. I imagine it needs a subselect...
thanks
Just use your current query as an inline view, and use the rows from that just like it was from a table.
e.g.
SELECT t.Count AS `duplicated`
, COUNT(1) AS `count`
FROM ( SELECT sku, COUNT(1) AS `Count` FROM products GROUP BY sku ) t
GROUP BY t.Count
MySQL refers to an inline view as a "derived table", and that name makes sense, when we understand how MySQL actually processes that. MySQL runs that inner query, and creates a temporary MyISAM table; once that is done, MySQL runs the outer query, using the temporary MyISAM table. (You'll see that if you run an EXPLAIN on the query.)
Above, I left your query just as you formatted it; I'd tend to reformat your query, so that entire query looks like this:
SELECT t.Count AS `duplicated'
, COUNT(1) AS `count`
FROM ( SELECT p.sku
, COUNT(1) AS `Count`
FROM products p
GROUP BY p.sku
) t
GROUP BY t.Count
(Just makes it easier for me to see the inner query, and easier to extract it and run it separately. And qualifying all column references (with a table alias or table name) is a best practice.)
select dup_count as duplicated,
count(*) as `count`,
group_concat(sku) as skus
from
(
SELECT sku, COUNT(1) AS dup_count
FROM products
GROUP BY sku
) tmp_tbl
group by dup_count

Mysql query to find distinct rows shows incorrect result

I wish to find the total number of distinct records in a table.
I have a table with the following columns
id, name, product, rating, manufacturer price
This has around 128 rows with some duplicates based on different column names.
I only want to select distinct rows:
select distinct name, product, rating, maufacturer, price from table
This returns 47 rows
For pagination purposes, I need to find the total number of distinct records, so I have another satatement:
select distinct count(name), product, rating, maufacturer, price from table
But this returns 128 instead of 47.
How can I get the total number of distinct rows? Any help will be much appreciated. Thanks
You have the distinct and count reversed.
SELECT COUNT(DISTINCT column_name) FROM table_name
Also, I would drop the extra fields when counting, your results will be unexpected for those other fields.
It is not quite clear if you want to get the count in the SAME query with the results or if you want to run a different query. Here go both solutions. In the result as a new column:
select distinct name, product, rating, manufacturer, price, (
select count(*) from (
select distinct name, product, rating, manufacturer, price from table1
) as resultCount) as resultCount
from table1
Notice the previous solution will repeat the count(*) for each row, which is not very efficient, not even visually appealing. Try running two queries one getting the actual data and the other one to get the amount of records in the table that match that data:
select distinct name, product, rating, manufacturer, price from table1
select count(*) from (
select distinct name, product, rating, manufacturer, price from table1
) as result
Hope this helps
Try adding GROUP BY name, product, rating, maufacturer, price clause
It would require running your actual query TWICE... an INNER for distinct and then get the count of those as a single row returned, and then join that to the original select distinct...
select distinct
t1.product,
t1.rating,
t1.maufacturer,
t1.price,
JustTheCount.DistCnt
from
table t1,
( select count(*) as DistCnt
from ( select distinct
t2.product,
t2.rating,
t2.maufacturer,
t2.price
from
table t2 )
) JustTheCount
In the following query, you're getting rows with distinct names since the DISTINCT clause precedes the name column:
SELECT DISTINCT name, product, rating, maufacturer, price FROM table
However, to get the count of the same records, use the following format:
SELECT COUNT(DISTINCT name) FROM table
Notice that DISTINCT goes inside of the COUNT function so that you're counting the distinct names. You probably don't want to include the other columns in the count query because they will be a random sample from the set. Of course, if you want a random sample, then include them.
Most applications will run the count query first, followed by the query to return the results. Also keep in mind that COUNT(*) is only an estimate, and the value may differ from the actual number of records returned.
SELECT DISTINCT COUNT(name), product FROM table isn't even a valid query in MySQL 4.x. You can't mix aggregate and non-aggregate columns. IN 5.x, it'll run, but the values for the non aggregate columns will be a random sample from the set.
At the risk of sparking some flames here.. you could always use:
SQL_CALC_FOUND_ROWS as the first part of your SQL. This is very mysql specific though.
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();