MYSQL JOIN WHERE ISSUES - need some kind of if condition - mysql

Well this will be hard to explain but ill do my best
The thing is i have 4 tables all with a specific column to relate to eachother.
1 table with users(agent_users) , 1 with working hours(agent_pers), 1 with sold items(agent_stat),1 with project(agent_pro)
the user and the project table is irrelevant in the issue at hand but to give you a better understanding why certain tables is included in my query i decided to still mention them =)
The thing is that I use 2 pages to insert data to the working hour and the sold items during that time tables, then i have a third page to summarize everything for current month, the query for that is as following:
SELECT *, SUM(sv_p_kom),SUM(sv_p_gick),SUM(sv_p_lunch) FROM ((
agent_users
LEFT JOIN agent_pers ON agent_users.sv_aid = agent_pers.sv_p_uid)
LEFT JOIN
agent_stat ON agent_pers.sv_p_uid = agent_stat.sv_s_uid)
LEFT JOIN
agent_pro ON agent_pers.sv_p_pid=agent_pro.p_id
WHERE MONTH(agent_pers.sv_p_datum) =7 GROUP BY sv_aname
so the problem is now that i dont want sold items from previous months to get included in the data received, i know i could solve that by simple adding in the WHERE part MONTH(agent_stat.sv_s_datum) =7 but then if no items been sold that month no data at all will show up not the time or anything. Any aid on how i could solve this is greatly appreciated. if there's something that's not so clear dont hesitate to ask and ill try my best to answer. after all my english isn't the best out there :P
regards
breezer

Fair enough :) -- put the condition as a second condition in your JOIN clause. ON (agent_pers.sv_p_uid = agent_stat.sv_s_uid AND agent_stat.sv_s_datum = 7)

Is your data such that you could add (MONTH(agent_stat.sv_s_datum) =7 OR agent_stat.sv_s_datum IS NULL) to the WHERE clause?

Related

SQL Outer Join Time Series with Data in Different Times

I was trying to combine multiple Cash Flows table for multiple projects into one table using SQL. The query i was using is listed below,
SELECT a.DATE1, b.DATE2, a.CF1, b.CF2
FROM a
FULL OUTER JOIN b
ON b.DATE2= a.DATE1
and the result table is listed below,
Since cash flows are taken place in different date for different project, some of them might happen in same day, some might not. I am wondering how can I adjust my code so that the result will looks like this,
Where we combine first 2 date columns. Keep the date value if the other one is NULL, and remove duplicated values if cash flows happened on the same day.
Since there are multiple projects I will need to combine, the method should be robust for expansion.
I have tried to use following,
SELECT ISNULL(a.DATE1, '') + ISNULL(b.DATE2, ''), a.CF1, b.CF2
FROM ...
However, this only solves the NULL part, and will actually add up duplicated date, and result in a new date.
Any help is appreciated, and thanks a lot in advance!
Try This using coalesce().
SELECT coalesce(a.DATE1, b.DATE2)as date, a.CF1, b.CF2
FROM a
FULL OUTER JOIN b
ON b.DATE2= a.DATE1

Not sure where I went wrong on a sql join

The most programming I do is shell scripts or some python or perl, so I have a basic understanding after Googling for a bit. A little background on what i’m doing. We have two inventory systems: Our’s and Their’s. I need to pull information from Their’s to compare with Our’s.
The problem: We need UPC’s to do inventory while They provide SKU’s in their monthly inventory report.
The solution: Join 3 tables. I’m using phpmyadmin to manage a mysql backend on a recent install of Debain Wheezy.
The first query takes every SKU They have in Their inventory, compares it with the UPC in Their listings and, since not every ‘UPC’ is actually a UPC, compares it to the UPC in Our listings. It looks like this:
SELECT TheirListings.upc, SUM(TheirInventory.quantity)
FROM TheirInventory
JOIN TheirListings
ON TheirListings.sku = TheirInventory.sku
JOIN OurListings
ON TheirListings.upc = OurListings.Upc
GROUP BY TheirListings.upc
ORDER BY TheirListings.upc
And it seems to work well. Our system is happy with it and it makes me happy because this reduces manual entry by 96%. Now I need to get everything this didn’t catch: the 4% that does need manual entry. Our tables shortened for brevity like this:
TheirListings TheirInventory OurListings
upc sku upc
sku quantity
I need to select all the SKU’s and associated quantities:
SELECT TheirInventory.sku, SUM(TheirInventory.quantity)
FROM TheirInventory
LEFT OUTER JOIN TheirListings
ON TheirListings.sku = TheirInventory.sku
LEFT OUTER JOIN OurListings
ON TheirListings.upc = OurListings.upc
WHERE OurListings.upc IS NULL
OR TheirListings.upc IS NULL
GROUP BY TheirInventory.sku
ORDER BY TheirInventory.sku
To double check it’s catching the remainder, I did SELECT COUNT(TheirInventory.sku) for both of those queries and another to return the total of sku’s. Adding my two queries gives me exactly 1 more than expected. I’m not sure where I went wrong.
The first thing I would guess is that they're not working on the same datasets. If you ran the first one a few days ago, perhaps some data has changed causing it to show up in the second query?
If not, what I would do is
SELECT SKU
FROM TheirInventory
WHERE SKU IN (<1st query>)
AND SKU IN (<2nd query>)
This will tell you what is showing up in both, and you can diagnose from there.

Need one chart with data not compared to each other

Ok - I'm rewording my question in hopes of getting as response. I (with help from a co-worker) have created the following SQL query that pulls the EXACT results that I need to appear in an SSRS chart:
select
(SELECT pfsp.SavingsGoal
FROM Projects AS p INNER JOIN
Projects_PerformanceServicesProject AS pfsp ON p.Id = pfsp.Id INNER JOIN
ProjectSavingsGoalTypes AS gt ON pfsp.ProjectSavingsGoalType_Id = gt.Id
WHERE (p.Id = #Project_ID)) as SavingsGoal,
(SELECT
Sum(identifiedSum)
FROM #Yaks where UPPER(name) = 'DECLINED'
GROUP BY name)as IdentifiedDeclined,
(SELECT
Sum(identifiedSum)
FROM #Yaks) as identifiedTotal,
(SELECT
Sum(implementableSum)
FROM #Yaks where upper(name) = 'APPROVED'
GROUP BY name) as implementableSavingsApproved,
(SELECT
Sum(implementedSum)
FROM #Yaks
) as implementedSavingsTotal
What the chart should ultimately look like (generally speaking):
http://i1365.photobucket.com/albums/r745/twarden11/chart_mockup_zps22cfdbf3.png
Telling you everything I've tried would take all my characters, and would be good for a laugh, and that's about it. It was also be futile, as I am an extreme novice (this is my first time to build a chart - ever, please be clear and speak in non-technical terms when possible), and my efforts I can assure had nothing to do with what I need to be trying.
So what I need are plain instructions on how to turn this query into the table graphic that I've included. I can't express how desperate I am at this point. My co-worker said it would be easier to simply pull the exact data that I need in the query, but never told me how to convert the query to a chart.
Thanks so much.
I would redesign the SQL query to return 2 columns and 5 rows. The 1st column would describe the category e.g. Goal, Identified etc. The 2nd column would present the $ values.
This would probably require a series of SELECT ... UNION ALL ... clauses, one for each of the 5 rows required.
Then I would add the 1st column to the chart as the Category Group, and the 2nd column as the Values (series).

MYSQL Query fails on Left join

I am in fight with an sql query i cant seem to figure out, and hope somebody might help me with this.
I got two tables i want to have connected together. My first table is the 'achievement' table, which has 3 fields: achievementId, AchievementName and ZoneId
My second table is a table that is in between my User and this achivement table, which stores basically also 3 items. The UserId, AchievementId and IsChecked. It refers here to a checkbox.
So I am working on a page that shows all the achievements in the form of a checkbox list, so I want to have those who are already achieved to be shown in the list, however, the query i am trying to get fails completely and I have no idea how to fix it. I tried the below item, but off course I failed miserable. So I was hoping if you guys could help me out here and adjust my query.
My current query is
Select * from Achievement
Where Zone = '2'
LEFT JOIN Achievement_User
Where Achievement_User.UserId='2'
And Achievement_User.AchievementId = Achievement.AchievementId
but it fails off course. I probably have the syntax wrong, but I cant figure it out. If somebody could help me out?
EDIT I think i explained this wrong. But the left join shows only the ones that match, however, I need the full list of the achievement, which is like 40 rows, it only shows now the rows where there is data from the Achievement_User with the query supplied by #Aquillo. I prefer ot have all 40 rows supplied by the Achivements with zone 2
First you have two WHERE-clauses, secondly a JOIN is a JOIN ON. Try this:
Select *
from Achievement
LEFT JOIN Achievement_User ON Achievement_User.AchievementId = Achievement.AchievementId
Where Zone = '2'
Update in response to OP's update
In that case you shouldn't use a restriction on the UserID, try the above query.

a small SQL query problem with SELECT

SQL queries are still my weakest point, so here I am with yet another SQL question.
Imagine I have two tables: auctions and bids. Table auctions contains my auctions and table bids contains the list of bids for each auction.
Now I'm selecting values like this:
SELECT
`auction_title`,
`auction_seo_title`,
`auction_description_1`,
`auction_unixtime_expiration`,
`auction_startPrice`,
MAX(`bids`.`bid_price`) as `bid_price`
FROM
`auctions`
LEFT JOIN `bids` ON `auctions`.`auction_id`=`bids`.`bid_belongs_to_auction`
ORDER BY
`auction_unixtime_expiration`
ASC
LIMIT 5
The query works, but it's got a little catch to it: It selects only those auctions, which have at least one corresponding value inside the bids table. That means that if I have a new auction, which has no bids yet, the query doesn't return this auction, but I want it too!
I believe this is a very simple problem for anyone with at least above average SQL skills. I hope someone like that comes around :) Thanks in advance!
SELECT
`auction_title`,
`auction_seo_title`,
`auction_description_1`,
`auction_unixtime_expiration`,
`auction_startPrice`,
MAX(`bids`.`bid_price`) as `bid_price`
FROM
`auctions`
LEFT JOIN `bids` ON `auctions`.`auction_id`=`bids`.`bid_belongs_to_auction`
GROUP BY `auction_id`
ORDER BY `auction_unixtime_expiration` ASC
Give that a try. Assuming that works, you can add your LIMIT on to the end.