How to get data of another table in mysql? - mysql

Table 1: kpi_detail column[redValue, amberValue, greenValue]
Table 2: data_detail
$sql= "SELECT id,kpi_code,kpi_name,result_data,target, count_date, SUM(result_data) AS total_data, assign FROM data_detail GROUP BY kpi_code";
Expected table columns results:
id| kpi_code | kpi_name | result_data | target | count_date | total_data | assign | redValue | amberValue | greenValue |
It looks like the GROUP BY is giving me trouble on joining two tables. How do I get the 3 columns of table1 kpi_detail? Join the 3 columns from table 2 to table 1

You have "bare" columns in the GROUP BY. You should be using aggregation functions for all the columns not in the GROUP BY:
SELECT MAX(id), kpi_code, MAX(kpi_name), MAX(result_data),
MAX(target), MAX(count_date), SUM(result_data) AS total_data,
MAX(assign)
FROM data_detail
GROUP BY kpi_code

Related

MySQL SELECT Query with WHERE clause Not returning rows from two tables

I have two tables InvoicePDF and UserMaster. They are connected using a common column (CompanyID). When I try to run the below query, I am getting empty result set. Curious to know why?
By the way I wish to return all the rows of the first table matching the CompanyID in the second table where the CustomerID is 3.
SELECT A.CompanyID,
B.COMPANYID,
B.CUSTOMERID,
A.InvPDFFileName,
A.InvMonth,
A.InvYear,
A.InvoiceID
FROM InvoicePDF A, UserMaster B
WHERE B.CompanyID=A.CompanyID and B.CustomerID=3
use left join and apply your condition B.CustomerID=3 in ON Cluase - and always use an explicit join instead of implicit one
SELECT A.CompanyID,B.COMPANYID,
B.CUSTOMERID,A.InvPDFFileName,
A.InvMonth,A.InvYear,A.InvoiceID
FROM InvoicePDF A left join UserMaster B on B.CompanyID=A.CompanyID and B.CustomerID=3
Your query works as expected
DROP TABLE IF EXISTS INVOICEPDF,USERMASTER;
CREATE TABLE INVOICEPDF(COMPANYID INT , InvPDFFileName varchar(3),InvoiceID int);
create table usermaster(COMPANYID int,CUSTOMERID int);
insert into invoicepdf values
(1,'aaa',1),(2,'bbb',2),(1,'aaa',3);
insert into usermaster values
(1,3),(2,4),(3,3);
SELECT A.CompanyID,
B.COMPANYID,
B.CUSTOMERID,
A.InvPDFFileName,
#A.InvMonth,
#A.InvYear,
A.InvoiceID
FROM InvoicePDF A, UserMaster B
WHERE B.CompanyID=A.CompanyID and B.CustomerID=3;
+-----------+-----------+------------+----------------+-----------+
| CompanyID | COMPANYID | CUSTOMERID | InvPDFFileName | InvoiceID |
+-----------+-----------+------------+----------------+-----------+
| 1 | 1 | 3 | aaa | 1 |
| 1 | 1 | 3 | aaa | 3 |
+-----------+-----------+------------+----------------+-----------+
2 rows in set (0.00 sec)
Which means one or more of your where conditions is false.

SUM() over a many-to-many relation in MYSQL

I have tables stanje and transakcija in a many-to-many relation, as shown in the image:
I need a MYSQL clause that returns all rows in stanje joined by a SUM() of every transakcija.iznos connected to a given stanje .
So far I have tried
select SUM(t.iznos)
from transakcija t
where transakcija_id in
(select transakcija_id from stanje_transakcija where stanje_id = ?)
which returns the SUM() correctly when given a stanje_id, but have no idea how to proceed, since I need sums for all rows in stanje.
Edit: added example output
------------------------------------
| stanje_id | naziv | SUM(t.iznos) |
------------------------------------
| 1 | a | 125.2 |
| 2 | b | -42.2 |
------------------------------------
If I understand correctly, you need to use JOIN in thoes tables by transakcija_id column and stanje_id column.
From your expect result you can try to use SUM with GROUP BY
select t2.stanje_id,t2.naziv,SUM(t.iznos)
from transakcija t
INNER JOIN stanje_transakcija t1 on t.transakcija_id = t1.transakcija_id
INNER JOIN stanje t2 on t2.stanje_id = t1.stanje_id
GROUP BY t2.stanje_id,t2.naziv

ORDER BY does not work if COUNT is used

I have a table with following content
loan_application
+----+---------+
| id | user_id |
+----+---------+
| 1 | 10 |
| 2 | 10 |
| 3 | 10 |
+----+---------+
I want to fetch 3rd record only if there are 3 records available, in this case i want id 3 and total count must be 3, here is what i expect
+--------------+----+
| COUNT(la.id) | id |
+--------------+----+
| 3 | 3 |
+--------------+----+
Here is the query i tried.
SELECT COUNT(la.id), la.id FROM loan_application la HAVING COUNT(la.id) = 3 ORDER BY la.id DESC;
However this gives me following result
+--------------+----+
| COUNT(la.id) | id |
+--------------+----+
| 3 | 1 |
+--------------+----+
The problem is that it returns id 1 even if i use order by id descending, whereas i am expecting the id to have value of 3, where am i going wrong ?
Thanks.
In your case u can use this query:
SELECT COUNT(la.id), max(la.id) FROM loan_application la
GROUP BY user_id
I try your table in my db MySQL
When you have a group by function (in this instance count()) in the select list without a group by clause, then mysql will return a single record only with the function applied to the whole table.
Mysql under certain configuration settings allow you to include fields in the select loist which are not in the group by clause, nor are aggregated. Mysql pretty much picks up the 1st value it encounters while scanning the data as a value for such fields, in your case the value 1 for id.
If you want to fetch the record where id=count of records within the table, then I would use the following query:
select *
from loan_application
join (select count(*) as numrows from loan_application) t
where id=t.numrows and t.numrows=3
However, this implies that the values within the id field are continuous and there are no gaps.
You are selecting la.id along with an aggregated function (COUNT). So after iterating the first record the la.id is selected but the count goes on. So in this case you will get the first la.id not the last. In order to get the last la.id you need to use the max function on that field.
Here's the updated query:
SELECT
COUNT(la.id),
MAX(la.id)
FROM
loan_application la
GROUP BY user_id
HAVING
COUNT(la.id) = 3
N:B: You are using COUNT without a GROUP BY Function. So this particular aggregated function is applied to the whole table.

how to get distinct result in sql?

I am trying to get distinct result of following table
id | name | created_on
1 | xyz | 2015-07-04 09:45:14
1 | xyz | 2015-07-04 10:40:59
2 | abc | 2015-07-05 10:40:59
I want distinct id with latest created_on means following result
1 | xyz | 2015-07-04 10:40:59
2 | abc | 2015-07-05 10:40:59
How to get above result by sql query?
Try this:
Select id, name, max(created_on) as created_on from table group by id
Try:
select id,max(name), max(created_on) from table_name group by id
Additional Note:
As it appears, your table is not normalized. That is, you store the name along with id in this table. So you may have these two rows simultaneously:
id | name | created_on
1 | a | 12-12-12
1 | b | 11-11-11
If that state is not logically possible in your model, you should redesign your database by splitting this table into two separate tables; one for holding id-name relationship, and another to hold id-created_on relationship:
table_1 (id,name)
table_2 (id,created_on)
Now, to get last created_on for each id:
select id,max(created_on) from table_2
And if you want to hold name in the query:
select t1.id, t1.name, t2.created_on from table_1 as t1 inner join
(select id, max(created_on) as created_on from table_2) as t2
on t1.id=t2.id
Assuming that id/name is always a pair:
select id, name, max(created_on)
from table
group by id, name;
It is safer to include both in the group by. I also find it misleading to name a column id when it is not unique for the table.
You can use the keyword DISTINCT
like
SELECT DISTINCT

getting count of each category filtered by another table's field

I have tables with the following structure.
AD_TABLE -
ID|NAME|CAT_ID|TYPE
1| car | C0101|Sale
2|bike | C0201|Want
CAT_TABLE -
ID |NAME |PARENT|LEVEL
C0100|Vehicle |C0100 | 0
C0101|Car |C0100 | 1
C0200|Bike/Scooters |C0100 | 1
C0201|Bike |C0200 | 2
C0202|Scooter |C0200 | 2
I need to get the count of ADs from each category, I have written the following query.
SELECT `CAT_TABLE`.`ID`,`CAT_TABLE`.`NAME`,`CAT_TABLE`.`LEVEL`,`CAT_TABLE`.`PARENT`, COUNT(`AD_TABLE`.`ID`)
FROM `CAT_TABLE`
LEFT JOIN `AD_TABLE` ON `AD_TABLE`.`CAT_ID`=`CAT_TABLE`.`ID`
WHERE (`CAT_TABLE`.`ID`='C0100' OR `CAT_TABLE`.`PARENT`='C0100') AND `AD_TABLE`.`TYPE`='0'
GROUP BY `CAT_TABLE`.`ID`
I got the count of each categories properly but after including the AD_TABLE.TYPE`='0' in the where clause categories which do not have ADs were ignored. I need to get all the categories even if the count is 0.
try this
SELECT `CAT_TABLE`.`ID`,`CAT_TABLE`.`NAME`,`CAT_TABLE`.`LEVEL`,`CAT_TABLE`.`PARENT`, COUNT(`AD_TABLE`.`ID`)
FROM `CAT_TABLE`
LEFT JOIN `AD_TABLE`
ON `AD_TABLE`.`CAT_ID`=`CAT_TABLE`.`ID`
AND `AD_TABLE`.`TYPE`='0' -- Write and here..<br/>
WHERE (`CAT_TABLE`.`ID`='C0100' OR `CAT_TABLE`.`PARENT`='C0100')
GROUP BY `CAT_TABLE`.`ID`