I have a point system and I'm trying to add them together. They are on two different tables and I'm using a subquery to get both totals and add them together. Both subqueries on their own work fine, but adding them together gives me a far greater number than it's supposed to.
Here's my query:
SELECT (SUM(tbl_achieve.achieve_points)+SUM(tbl_assign.assign_points))
FROM
(SELECT DISTINCT(tbl_achievements.achieve_id), tbl_achievements.achieve_points FROM tbl_achievements INNER JOIN tbl_studentachieve ON tbl_studentachieve.achieve_id = tbl_achievements.achieve_id AND tbl_studentachieve.student_ID = 8 AND tbl_achievements.achieve_cat = "main" ) as tbl_achieve,
(SELECT DISTINCT(tbl_assignments.assign_id), assign_points FROM tbl_assignments INNER JOIN tbl_studentassign ON tbl_studentassign.assign_id = tbl_studentassign.assign_id WHERE tbl_assignments.assign_cat = "main" AND tbl_studentassign.student_id = 8 AND tbl_studentassign.assign_status = "submitted") as tbl_assign
I think what the problem is, is that it puts both row counts together. So instead of having 2 rows of 10 points, I have 10 rows of 10 points because of the other table's number.
Any idea what I could be missing?
This one is going to be tough without knowing anything about your database. I ran the following query:
select SUM(feed_id) + SUM(user_id) FROM events where 1
on my own db and it returns the correct addition of those complete rows together as only one row. It sounds like that is not what you want, but that is the expected behavior of mySQL. perhaps a more detailed explanation of what you're looking for would help to get you where you need to be. Cheers...
Related
I have two tables and I want to fetch select columns from the tables.
table 1 is sfpinventoryinfo and table 2 is opticalportinfo.
Both have NEID as common.
SELECT
sfpinventoryinfo.NEID,
sfpinventoryinfo.SlotNumber,
sfpinventoryinfo.PortNo,
sfpinventoryinfo.PortType,
sfpinventoryinfo.`Type`,
sfpinventoryinfo.SN,
sfpinventoryinfo.GenDes,
sfpinventoryinfo.ApplicationCode,
opticalportinfo.ChannelFrequency
FROM
sfpinventoryinfo
JOIN
opticalportinfo ON sfpinventoryinfo.NEID = opticalportinfo.NEID;
But I am getting weird results:
As shows above result, Slot no 4 should have only 1 entry for port instead of 5
It's likely your opticalportinfo has six rows with the value 13 in NEID. So, your join produces all six rows in your result set.
It's hard to guess the "right" way to choose which of those six rows to use without knowing more about your application. You can hack around the problem with SELECT DISTINCT if you must. But it's a hack.
You clearly have duplicates in one or both tables. In your example data, the entire row looks duplicated, so you could use select distinct so entire rows are not repeated:
SELECT DISTINCT i.NEID, i.SlotNumber, i.PortNo, i.PortType, i.`Type`, i.SN,
i.GenDes, i.ApplicationCode, oi.ChannelFrequency
FROM sfpinventoryinfo i JOIN
opticalportinfo op
ON i.NEID = oi.NEID;
Or perhaps GROUP BY:
SELECT i.NEID, i.SlotNumber, i.PortNo, i.PortType, i.`Type`, i.SN,
i.GenDes, i.ApplicationCode, MAX(oi.ChannelFrequency)
FROM sfpinventoryinfo i JOIN
opticalportinfo op
ON i.NEID = oi.NEID
GROUP BY i.NEID, i.SlotNumber, i.PortNo, i.PortType, i.`Type`, i.SN,
i.GenDes, i.ApplicationCode;
That said, you really need to understand why there are duplicates and adjust your query or fix your data.
I appreciate that questions similar to this one have been asked on here before but I have thus far been unable to implement the answers provided into my code both because of wanting to distinguish duplicates in one column only whilst the other stays the same and the INNER JOIN in my code. The INNER JOIN is problematic because most of the provided answers use the PARTITION function and, being a novice with SQL, I do not know how to integrate this with it. Advice just on using INNER JOIN with PARTITION would be useful.
Whilst I could do this post-export in Python (where I will be using the desired output), this code currently outputs ~2 million rows, making it time-consuming to work with and check. Here is the code:
SELECT client_ip_address, language_enum_code
FROM vw_user_session_log AS usl
INNER JOIN vw_user_topic_ownership AS uto
ON usl.user_id = uto.user_id
Using SELECT DISTINCT instead of SELECT gets me closer to the desired output but rather than leaving one duplicate row behind it removes all of them. Advice on using this function whilst preserving one of the duplicate rows would be preferred. I am on a read-only connection to the database so the DELETE FROM approach seen here would only be viable if I could make a temporary query-able table from the query output which I don't think is possible and seems clumsy.
Raw data sample:
user_id: client_ip_address: language_enum_code: (other stuff...)
4 194:4:62:18 107
2 101:9:23:34 14
3 180:4:87:99 15
3 194:4:62:18 15
4 166:1:19:27 107
2 166:1:19:27 14
Desired result:
user_id: client_ip_address: language_enum_code: (other stuff...)
4 194:4:62:18 107
2 101:9:23:34 14
3 180:4:87:99 15
As you can see, any id-enum combination should be filtered to occur only once. The reason this is not any ip-enum combination is that multiple users can connect through the same IP address.
If you don't care which IP address you keep for each user_id / enum combo, then something like this should do:
SELECT user_id, min(client_ip_address), language_enum_code
FROM vw_user_session_log AS usl
INNER JOIN vw_user_topic_ownership AS uto
ON usl.user_id = uto.user_id
where client_ip_address is not null
group by user_id, language_enum_code
Do you simply want aggregation?
SELECT client_ip_address, GROUP_CONCAT(DISTINCT language_enum_code)
FROM vw_user_session_log usl INNER JOIN
vw_user_topic_ownership uto
ON usl.user_id = uto.user_id
GROUP BY client_ip_address;
This will return one row per client_ip_address with each language code in a comma delimited list.
You can also use MIN() or MAX() to get an arbitrary value for language_enum_code for each client_ip_address.
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).
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.
I'm having an issue getting this SQL query to work properly.
I have the following query
SELECT apps.*,
SUM(IF(adtracking.appId = apps.id AND adtracking.id = transactions.adTrackingId, transactions.payoutAmount, 0)) AS 'revenue',
SUM(IF(adtracking.appId = apps.id AND adtracking.type = 'impression', 1, 0)) AS 'impressions'
FROM apps, adtracking, transactions
WHERE apps.userId = '$userId'
GROUP BY apps.id
Everything is working, HOWEVER for the 'impressions' column I am generating in the query, I am getting a WAY larger number than there should be. For example, one matching app for this query should only have 72 for 'Impressions' yet it is coming up with a value of over 3,000 when there aren't even that many rows in the adtracking table. Why is this? What is wrong here?
Your problem is you have no join conditions, so you are getting every row of every table being joined in your query result - called a cartesian product.
To fix, change your FROM clause to this:
FROM apps a
LEFT JOIN adtracking ad ON ad.appId = a.id
LEFT JOIN transactions t ON t.adTrackingId = ad.id
You haven't provided the schema for your tables, so I guessed the names of the relevant columns - you may have to adjust them. Also, your transaction table may join to adtracking - it's impossible to know from your question, so agin you have have to alter things slightly. Hopefully you get the idea.
Edit:
Note: your group-by clause is incorrect. You either need to list every column of apps (not recommended), or change your select to only select the id column from apps (recommended). Change your select to this:
SELECT apps.id,
-- rest of query the same
Otherwise you'll get weird, incorrect, results.