I'd like to have sql results containing dynamically added fields. The picture I attached explains what I aim at.
As far I've made up something like below, yet it doesn't work.
SELECT s.num, s.name ( SELECT g.grade AS g.subject FROM grades g WHERE g.student = s.id ) FROM students s;
Note that I want to have column name corresponding to value of column subject.
I have no idea how to get it.
You will need to construct Dynamic Sql with prepared statements.
http://blog.sqlauthority.com/2014/06/20/mysql-dynamic-sql-with-execute-and-prepare-statements/
The columns would come back like "as history" ... "as math"
As far as the nulls that is just common outer join action
Related
Good afternoon,
I am creating a database for handling safety at my workplace.
I want to create a system where the user can raise a toolbox talk and through filters produce a list of employees who need to participate because they either belong to a certain department, certain competency or both.
To set the scene, an employee can be assigned multiple departments and multiple competencies in which case my select query: Query:ToolboxTalk works fine.
However there are occasions where an employee will be assigned to a department but maybe no competency. When this happens, my query does not return that employee because of the null value.
My question is this:
How can I make my query include null values or should I be going about this a different way?
Please see screenshot of my query in design view and SQL below:
SELECT tblEmployees.EmployeeID, IIf(IsNull([LastName]),IIf(IsNull([FirstName]),[FirstName]),IIf(IsNull([FirstName]),[LastName],[FirstName] & " " & [LastName])) AS [Employee Name], tblEmployees.Gender, tblDepartments.DepartmentID, tblDepartments.Department, tblCompetencies.CompetencyID, tblCompetencies.CompetencyDescription, tblEmployeesDepartments.EmployeesDepartmentID, tblEmployeesCompetencies.EmployeeCompetencyID
FROM (tblEmployees INNER JOIN (tblCompetencies INNER JOIN tblEmployeesCompetencies ON tblCompetencies.CompetencyID = tblEmployeesCompetencies.CompetencyID) ON tblEmployees.EmployeeID = tblEmployeesCompetencies.EmployeeID) INNER JOIN (tblDepartments INNER JOIN tblEmployeesDepartments ON tblDepartments.DepartmentID = tblEmployeesDepartments.DepartmentID) ON tblEmployees.EmployeeID = tblEmployeesDepartments.EmployeeID
WHERE (((tblEmployees.EmploymentStatus)="Active"));
Query-Design View Image
If there is any info I have neglected to include, please let me know and Ill endeavour to add it.
Thank you in advance!
Solution was to adjust query to left join with normalised table structure.
Refer picture and sql.
Query design view
Query SQL view
Brief Explanation of problem:
I'm currently trying to create a report (RDL file) in visual studio that gets all the phone calls for a specific case, and prints them out in 2 tables that look like this: Current tables . My issue is that when I run the report, it is grabbing information from every case, instead of the particular case I'm currently in.
Here is the query I'm using to get the information for the tables:
SELECT
FilteredPhoneCall.regardingobjectidname,
FilteredPhoneCall.icms_contactname,
FilteredPhoneCall.owneridname,
FilteredPhoneCall.icms_callendtime,
FilteredPhoneCall.icms_informationgathered,
Filteredicms_impcase.icms_casenumber
FROM
FilteredPhoneCall,
Filteredicms_impcase
WHERE FilteredPhoneCall.regardingobjectidname
LIKE '%' + Filteredicms_impcase.icms_casenumber + '%'
How should I change my query so that it specifies that all information should be from a single case. Here are some pictures of the 2 tables I'm trying to join for clarity:
FilteredPhoneCall table and Filteredicms_impcase
Should I be using an inner join statement? Also let me clarify my thought process on why I'm using the LIKE statement is because of how the rows are in the system, the FilteredPhoneCall.regardingobjectidname is formatted like this: Name of company / CaseID, I need the 2nd half of that value, the CaseID in order to join the tables together to get the specific case value.
A)whether my syntax is working the way how I think it's working?
B)should I use a more specific identifier, like an INNER JOIN?
Don’t use “,” for joining 2 tables. It is worse than cross joins
Convert into Inner Join like below:
SELECT
FPC.regardingobjectidname,
FPC.icms_contactname,
FPC.owneridname,
FPC.icms_callendtime,
FPC.icms_informationgathered,
FC.icms_casenumber
FROM
FilteredPhoneCall FPC
INNER JOIN Filteredicms_impcase FC
ON FPC.regardingobjectid = FC.icms_casenumberid
WHERE FPC.regardingobjectidname
LIKE '%' + FC.icms_casenumber + '%'
I would transform the "regarding object id name" and perform the join explicitly:
SELECT
FilteredPhoneCall.regardingobjectidname,
FilteredPhoneCall.icms_contactname,
FilteredPhoneCall.owneridname,
FilteredPhoneCall.icms_callendtime,
FilteredPhoneCall.icms_informationgathered,
Filteredicms_impcase.icms_casenumber
FROM
FilteredPhoneCall
INNER JOIN Filteredicms_impcase
ON SUBSTRING_INDEX(FilteredPhoneCall.regardingobjectidname,'/',-1) =
Filteredicms_impcase.icms_casenumber
See this post for details: SQL SELECT everything after a certain character
Could someone please tell explain to me how to properly process a query that collects information from 2 tables, i thought I had this figured out until I added more records. Please look at the image I have below:enter image description here
(The last record should not have the name "Thomas Murray" in it)
Then there is the query I am processing:
"select a.*, b.forenames, b.surname FROM playerSkills a, playerdb b GROUP BY sheetNo"
What I was hoping to do is collect all from the playerSkills database (which it does) and only bring over the names from the second database (playerdb) that matched with the playerID but as I want to return more than one result so I don't know what to do as it returns the whole column and just pastes the one name into every field.
Though I am sure a JOIN is to be inserted here, I am not sure which or at all.
I am not experienced with SQL but trying to wrap my head around it. I have experimented with the JOIN clauses but didn't get far probably due to a syntax.
How can join the names to the playerID so they appear in the appropriate fields?
You need columns to join on . . . and proper join syntax:
select ps.*, p.forenames, p.surname
FROM playerSkills ps JOIN
playerdb p
ON ps.playerId = p.playerId;
Notes:
Your query does not require GROUP BY.
Your query does require JOIN conditions.
Kudos for using table aliases. They should be abbreviations for the table name.
You want to always use explicit JOIN syntax. No commas in the FROM clause.
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 wonder if any can help me understand something I'm trying to solve.
I'm working on a wordpress site but this is more a sql question as I'm just querying to get some results within a template file.
I have a gallery of pictures which are advert boxes, and I need to pull these in relation to a supplied movie name, to do this Im using some custom fields on the ad pic called 'adlink' (link off ad) and ad
I'm using the nextgen gallery plugin and querying those tables, and I have three tables in total that contain the data I need to query.
ngg_pictures, nggcf_field_values & nggcf_fields.
the nggcf tables are custom fields tables,
I have got so far I can get what I need in two seperate queries, but I can't combine these into one query as it means querying the nggcf_field_values table twice, which I can't seem to sort.
I have hardcoded the search criteria in for the mo, but the 'close-encounters' bit would be a passed var, and the '156' would be the pid from the first query.
SELECT `eg_ngg_pictures`.`filename`, `eg_nggcf_field_values`.`fid`, `eg_nggcf_field_values`.`pid`
FROM eg_ngg_pictures, eg_nggcf_field_values
WHERE ((`eg_nggcf_field_values`.`field_value` LIKE 'close-encounters') AND (`eg_nggcf_field_values`.`pid` = eg_ngg_pictures.pid))
SELECT `eg_nggcf_field_values`.`field_value`
FROM eg_nggcf_field_values, eg_nggcf_fields
WHERE ((`eg_nggcf_fields`.`field_name` = 'adlink') AND (`eg_nggcf_fields`.`id` = eg_nggcf_field_values.fid) AND (`eg_nggcf_field_values`.`pid` = '156'))
any help would be greatly appreciated, I can get the results with what I have, but I like to understand how to combine these two and write better SQl. Thanks MRO
After looking at the Wordpress extension, I think the eg_nggcf_fields is the table that contains the name for a custom field. The eg_nggcf_field_values table contains the values of that custom field per picture.
So if you're looking for two fields called moviename and adlink, you have to look up two rows in the field_values table. You can join a table twice if you give it a different alias:
select pic.filename
, pic.pid
, fv1.field_value as MovieName
, fv2.field_value as Adlink
from eg_ngg_pictures pic
inner join -- Find ID for the field called 'moviename'
eg_nggcf_fields f1
on f1.field_name = 'moviename'
inner join -- Find value for field moviename for this picture
eg_nggcf_field_values as fv1
on fv1.pid = pic.pid
and fv1.fid = f1.fid
inner join -- Find ID for the field called 'adlink'
eg_nggcf_fields f2
on f2.field_name = 'adlink'
inner join -- Find value for field adlink for this picture
eg_nggcf_field_values as fv2
on fv2.pid = pic.pid
and fv2.fid = f2.fid
where fv1.field_value like 'close-encounters'
First of all, I'd recommend sticking to modern ANSI syntax for JOINing tables, which means using the JOIN clause.
Instead of using:
FROM table1, table2 WHERE table1.id = table2.pid
use:
FROM Table 1 JOIN table2 ON table1.id = table2.id
For simplicity's sake, I'd also recommend you to alias tables, as that tends to make the code more readable. Instead of having to write out egg_ngg_pictures every time, you can simply refer to the alias you assign it instead.
Lastly, when you use a LIKE operator, you usually add a wild-card character (typically %. I.e. LIKE '%123' or LIKE '123%'). You seem to look only for complete matches, which means you can just stick to using =, as that should give you slightly better performance.
Now to rewrite your query, I'd use something like the following:
SELECT
pic.filename
, fieldval.fid
, fieldval.pid
, fieldval.field_value
FROM
eg_ngg_pictures pic
JOIN eg_nggcf_field_values fieldval ON fieldval.pid = pic.pid
JOIN eg_nggcf_fields fields ON fields.id = fieldval.fid
WHERE
((fieldval.field_value = 'close-encounters')
AND fields.field_name = 'ad_link'
Note that I am not able to test the query, as I do not have your schema. But by incorporating the two queries into a single query, the join on the field_Values.PID retreieved with the 'close_encounters' value should already exist.
If the query does not work, feel free to create a SQL fiddle with the relevant tables and some data, and I'll try and get it to work with that.