SUM() over a many-to-many relation in MYSQL - 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

Related

How to get data of another table in 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

SQL Union SELECT from two tables then combine to one row

I have two tables (tests and reserved) which reference each other it is a 1:1 relationship.
One test's ID is reserved for another test's ID which is in the same table but kept in the reserved table as a look up.
Here's some sample data:
tests:
test_id | summary_id | ref
1 | 1 | ref1
2 | 2 | ref2
reserved:
reserved_id | reserved_summary_id | reserved_for_summary_id
1 | 1 | 2
Currently I am using a UNION to get them both:
SELECT * FROM reserved r, tests t WHERE t.summary_id = r.reserved_summary_id
UNION
SELECT * FROM reserved r, tests t WHERE t.summary_id = r.reserved_for_summary_id
I have a fiddle here.
How can I combine that query into one row? I have tried this one from SO. But get an error.
Are you trying to JOIN the summary table twice with the the tests table so you can access the details of each reserved_summary and reserved_for_summary ?
If yes, then you need :
SELECT
r.reserved_id,
t1.ref ref_of_reserved_summary_id,
t2.ref ref_of_reserved_for_summary_id
FROM
reserved r
INNER JOIN tests t1 ON t1.summary_id = r.reserved_summary_id
INNER JOIN tests t2 ON t2.summary_id = r.reserved_for_summary_id
This will return something like :
reserved_id | ref_of_reserved_summary_id | ref_of_reserved_for_summary_id
1 | ref1 | ref2
You can switch to LEFT JOIN to avoid filtering out records where one of the summaries is not registered in the tests table.

Combine rows from two tables with different columns?

I'm having a hard time wrapping my head around this one. I believe it's happening because I am joining the two separate tables based on the same column (user_id), but I don't know how to fix it because the only thing in common between the two tables IS the user_id column.
Here is the query.
SELECT users_data_existing.`date`,`message`,`action`,`status`,`data`,
users_data_new.`date`,`data_new`
FROM users_data_existing
INNER JOIN users_data_action USING (action_id)
INNER JOIN users_data_status_user USING (status_user_id)
INNER JOIN `users` USING (user_id)
INNER JOIN users_data_new USING (user_id)
INNER JOIN data ON users_data_existing.`data_id` = data.`id`
WHERE users_data_existing.`user_id` = 2
ORDER BY users_data_existing.`date`,users_data_new.`date` DESC
The result, is that the users_data_new.date and data_new columns, are concatenated or "appended" to the previous rows.
+----------+-----------+-----------+-----------+-----------+----------+-----------+
| date | message | action | status | data | date | data_new |
+----------+-----------+-----------+-----------+-----------+----------+-----------+
|2011-01-01| data | data | data | data |2011-01-02| data_new |
-----------------------------------------------------------------------------------
|2011-01-01| data | data | data | data |2011-01-03| data_new1 |
-----------------------------------------------------------------------------------
REPEATS PATTERN FOR TOTAL RECORDS IN users_data_new TABLE
+----------+-----------+-----------+-----------+-----------+----------+-----------+
| date | message | action | status | data | date | data_new |
+----------+-----------+-----------+-----------+-----------+----------+-----------+
|2011-01-01| data1 | data1 | data1 | data1 |2011-01-02| data_new |
-----------------------------------------------------------------------------------
|2011-01-01| data1 | data1 | data1 | data1 |2011-01-03| data_new1 |
-----------------------------------------------------------------------------------
But that's not what I need. How can I get the last two columns into a separate row? I think a UNION would resolve this but I can't do that because the tables are almost identical but don't share the message column.
As suspected in the question, it was a UNION that I needed. The trick was to create an empty column in users_data_new to match users_data_existing. I also had a challenge with sorting it so I will include that here as well.
(SELECT data_existing.date AS submitdate,status_user.status,action.action,
data.data,data_existing.message
FROM users_data_existing AS data_existing
INNER JOIN users_requested_status_user status_user
ON data_existing.status_user_id = status_user.status_user_id
INNER JOIN users_requested_action action
ON data_existing.action_id = action.action_id
INNER JOIN websites data
ON data_existing.data_id = data.id
ORDER BY data_existing.date DESC) //sorts sub-query
UNION ALL
(SELECT data_new.date AS submitdate,status_user.status,
action.action,data_new.data_new,'' message //needed to add this last empty column
FROM users_data_new AS data_new
INNER JOIN users_requested_status_user status_user
ON data_new.status_user_id = status_user.status_user_id
INNER JOIN users_requested_action action
ON data_new.action_id = action.action_id
ORDER BY data_new.date DESC) //sorts sub-query
ORDER BY submitdate DESC"; //sorts the entire result
Keep in mind that with the alias for the date, the associative array key will be whatever alias name you use. i.e. $result['submitdate']

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`

Duplicates in Database, Help Edit My Query to Filter Them Out?

I have just finished my latest task of creating an RSS Feed using PHP to fetch data from a database.
I've only just noticed that a lot (if not all) of these items have duplicates and I was trying to work out how to only fetch one of each.
I had a thought that in my PHP loop I could only print out every second row to only have one of each set of duplicates but in some cases there are 3 or 4 of each article so somehow it must be achieved by the query.
Query:
SELECT *
FROM uk_newsreach_article t1
INNER JOIN uk_newsreach_article_photo t2
ON t1.id = t2.newsArticleID
INNER JOIN uk_newsreach_photo t3
ON t2.newsPhotoID = t3.id
ORDER BY t1.publishDate DESC;
Table Structures:
uk_newsreach_article
--------------------
id | headline | extract | text | publishDate | ...
uk_newsreach_article_photo
--------------------------
id | newsArticleID | newsPhotoID
uk_newsreach_photo
------------------
id | htmlAlt | URL | height | width | ...
For some reason or another there are lots of duplicates and the only thing truely unique amongst each set of data is the uk_newsreach_article_photo.id because even though uk_newsreach_article_photo.newsArticleID and uk_newsreach_article_photo.newsPhotoID are identical in a set of duplicates, all I need is one from each set, e.g.
Sample Data
id | newsArticleID | newsPhotoID
--------------------------------
2 | 800482746 | 7044521
10 | 800482746 | 7044521
19 | 800482746 | 7044521
29 | 800482746 | 7044521
39 | 800482746 | 7044521
53 | 800482746 | 7044521
67 | 800482746 | 7044521
I tried sticking a DISTINCT into the query along with specifying the actual columns I wanted but this didn't work.
As you have noticed, the DISTINCT operator will return every id. You could use a GROUP BYinstead.
You will have to make a decision about wich id you want to retain. In the example, I have used MINbut any aggregate function would do.
SQL Statement
SELECT MIN(t1.id), t2.newsArticleID, t2.newsPhotoID
FROM uk_newsreach_article t1
INNER JOIN uk_newsreach_article_photo t2
ON t1.id = t2.newsArticleID
INNER JOIN uk_newsreach_photo t3
ON t2.newsPhotoID = t3.id
GROUP BY t2.newsArticleID, t2.newsPhotoID
ORDER BY t1.publishDate DESC;
Disclaimer
Now while this would be an easy solution to your immediate problem, if you decide that duplicates should not happen, you really should consider redesigning your tables to prevent duplicates getting into your tables in the first place.
group by all your selected columns with HAVING COUNT(*) > 1 will eleminate all duplicates like this:
SELECT *
FROM uk_newsreach_article t1
INNER JOIN uk_newsreach_article_photo t2
ON t1.id = t2.newsArticleID
INNER JOIN uk_newsreach_photo t3
ON t2.newsPhotoID = t3.id
GROUP BY t1.id, t1.headline, t1.extract, t1.text, t1.publishDate,
t2.id, t2.newsArticleID, t2.newsPhotoID,
t3.id, t3.htmlAlt, t3.URL, t3.height, t3.width
HAVING COUNT(*) > 1
ORDER BY t1.publishDate DESC;