where clause in COUNT function and joining two queries - mysql

I have a table that I am trying to count the number of course passed, and also list the modules passed as well.
The first problem I am having is what to put in the where variable, so that its not specific to a customer(I can use the query below for a particular customer and a particular course)but I will like a generic query where the result will be distinct in terms of user and course like the one below
SELECT FirstName
,LastName
,CourseTitle
,Noofmodules
,count(Coursecompleted) AS modulescompleted
FROM EStudentsprogress
WHERE Coursecompleted = '1'
AND EmailAddress = 'scascsc#e.co.uk'
AND CourseTitle = 'Microsoft MOS 2010 EXCEL'
GROUP BY FirstName
,LastName
,CourseTitle
,Noofmodules
How can I make it list the result as above, whereby I don't specify the email address or course title(trying to get the result for all the clients )
Also I have a query that list the courses that is passed by the customer, I will like the column with the list of courses passed be added to the result above, but as a column for each course.
SELECT FirstName
,LastName
,CourseTitle
,EmailAddress
,CourseModule AS coursepassed
FROM EStudentsprogress
WHERE coursecompleted = 1
Cheers

Can you not just add the email address and course title fields to the select fields and the GROUP BY clause.
Also you can use GROUP_CONCAT to bring back a field containing all the course modules.
Something like this:-
SELECT FirstName,
LastName,
CourseTitle,
Noofmodules,
EmailAddress,
CourseTitlecount,
COUNT(Coursecompleted) as modulescompleted,
GROUP_CONCAT(CourseModule) as modulescompletednames
FROM EStudentsprogress
WHERE Coursecompleted = '1'
GROUP BY FirstName, LastName, CourseTitle, Noofmodules, EmailAddress, CourseTitlecount ;

Related

RoR: How to merge an order on two columns into an ActiveRecord query?

I'm trying to sort a table based on several columns so that the resulting order represents the fields interlaced.
ie,
users has first_name:string and last_name:string, account has historical_first_name, and historical_last_name, and belongs to User. If user has a first_name, it should override historical_first_name when listing accounts (ie, a user either has set their name or they have a historical name on an account).
I'm trying to return an ordered list of accounts based on first name and last name ASC, either historical or set on the user. The result should be an ActiveRecord relation and not an array.
This query does not achieve what I want:
#accounts = #accounts.includes(:user).order("users.first_name ASC, historical_first_name ASC, users.last_name ASC, users.last_name ASC")
Because any historical_first_names are that are alphabetically before first_names are sorted after all first_name. How would you write something that achieves an order like this:
Amanda Adams <- migration_first_name: Amanda, user.first_name: nil
Bentley James <- migration_first_name: nil, user.first_name: Bentley
Cynthia Cann <- migration_first_name: Cynthia, user.first_name: nil
You want to order primarily by the first_name, or the historical_first_name if that is null. And then after that order by last_name, or historical_last_name if that is null.
You can use the COALESCE() function (or IFNULL()) to represent that.
#accounts = #accounts.includes(:user).order(
"COALESCE(users.first_name, users.historical_first_name) ASC",
"COALESCE(users.last_name, users.historical_last_name) ASC"
)

Don't want to fetch single column (name)

def fetchProposalByStudio(studioId: Int): List[ProposalDetails] = {
ConnectionPoolManager.getDB(config = appConfig).localTx { implicit session: DBSession =>
logger.info("Querying proposal table to fetch all the proposals")
SQL("""SELECT [except name] p.id, id, proposal_title, challenge, possible_solution, explanation,
| submission_date, status, submitted_by, remark
| FROM proposal p inner join knolder k on k.id = p.knolder_id
| where k.studio_id =? order by p.id desc""".stripMargin)
.bind(studioId)
.map(rs =>
ProposalDetails(
rs.int("id"),
rs.int("id"),
rs.string("proposal_title"),
rs.string("challenge"),
rs.string("possible_solution"),
rs.string("explanation"),
rs.string("submission_date"),
Some(ProposalStatus.withName(rs.string("status"))),
rs.string("submitted_by"),
rs.string("remark"),
**rs.string("name")**
)
)
.list().apply()
}
}
I don't want to fetch this column name in my query but without involving this in the query i am getting this error due to using case class.
13:28:24.446 [default-akka.actor.default-dispatcher-8] INFO c.k.l.b.ProposalImpl - Something went wrong while fetching the proposals. Exception message: ERROR: syntax error at or near "["
Position: 8
Smells of a syntax problem...
Perhaps:
SELECT [except name] -- should be
SELECT `except name` -- in mysql
If you don't want a particular column in an SQL resultset, you simply don't mention it in the SELECT.
There is no notion of SELECT * EXCEPT FirstName FROM person - if Person has FirstName, LastName, Age, Address and you don't want FirstName, you don't put it in the select list:
SELECT LastName, Age, Address FROM Person
^^^^^^^
no FirstName mentioned here
Mention every column you do want, do not mention any column you don't want.
If the complaint is "but there are 527 columns and I want all except one" - you can do something like:
SELECT CONCAT(column_name, ',') FROM information_schema.columns WHERE table_name = 'Person' and column_name <> 'FirstName'
which produces a resultset like:
LastName,
Age,
Address,
... 523 other columns
And you can then copy that resultset and paste it into your code, and it already has commas on the end..
If you want the columns all on one line, use GROUP_CONCAT or use a decent text editor to replace \r\n with nothing. If you want to surround the column name in backticks, put it into the CONCAT.. The ultimate point here is that you're a software developer: you can write code that writes code, then you can copy the output, which is valid code, and paste it into some other code somewhere else

Outer query value is not able use in inner query

SELECT
(select Email from Contact where AccountId = Account.Id),
Id,
BillingCity,
BillingCountry,
BillingPostalCode,
BillingState,
BillingStreet,
Name,
Phone
FROM Account
where
LastModifiedDate < #[flowVars['timestamp']]
Problem here is I am not able to get the Email which is present in the sub query based on the Id of current iteration. Can you please help on this
I'm not sure how you are running the query, and how you are accessing the result, but if you are doing it in a place that does not give you the result dynamically, meaning that you try to access the columns by expected name, i.e. trying to get the "email" column somehow, then you need to fix a small issue in the query.
You need to add the AS operator to give your subquery a meaningful name like email like so:
...
(select Email from Contact where AccountId = Account.Id) as email,
...
See fiddle here for working example: db-fiddle
You can get rid of the scalar sub-query and just put a join to the CONTACT table instead. The following assumes that the CONTACT table is an optional relationship.
SELECT
con.email,
acct.Id,
acct.BillingCity,
acct.BillingCountry,
acct.BillingPostalCode,
acct.BillingState,
acct.BillingStreet,
acct.Name,
acct.Phone
FROM account acct
LEFT OUTER JOIN
contact con ON con.account_id = acct.account_id
WHERE acct.LastModifiedDate < #[flowVars['timestamp']]

mysql - select from column with multiply values

I have this query
$r=mysql_query(
"SELECT *
FROM advertisements
WHERE
$filter exposure!='0' AND `status`='2' AND
(clicks_left_micro>0 OR clicks_left_mini>0
OR clicks_left_standard>0 OR clicks_left_extended>0
OR fixed='1')
ORDER BY
exposure DESC, fixed DESC"
);
In my advertisements table I have a column called geoFilter. That column can either be empty or it can contain values (country codes) like:
DK, US, CA, EN,
I get the users country code like this (stored in DB):
$userdata['country_code'];
My question is, how can I select from the advertisements table where users country code is present?
You can try to start your WHERE clause with: WHERE country_code LIKE „%US%“ AND (…) to get only results where US is contained in the country_code column.

Multiple mysql joins, how to combine these 2 select statments

I have 2 select statements I would like to combine into one, though I really only need the info from one field in the second select statement(The field data from user_info_data). The fields I need are Firstname, lastname, email, course fullname, role, and the field data where fieldid = '15'. The first select statement will give me everything but the data field. And the second gives me everything but the course. I tried doing the second select statement similar to Role field but it complains about it returning more than one row. If I try and just use the course name without the fieldid='15' part, it brings up over 100k records(Each user shows up in each course and all their data).
Fields for tables:
user(id,auth,confirmed,policyagreed,username,password,idnumber,firstname,lastname,email,phone etc..)
user_info_data(id,userid,fieldid,data)
role(id,name,shortname,description,sortorder)
role_assignments(id,roleid,contextid,userid...)
context(id,contextlevel,instanceid,path,depth)
First statement:
SELECT user.firstname AS Firstname, user.lastname AS Lastname, user.email AS Email, course.fullname AS Course, role.name AS Role
FROM user AS user, course AS course,role,role_assignments AS asg
INNER JOIN context AS context ON asg.contextid=context.id
WHERE context.contextlevel = 50
AND role.id=asg.roleid
AND user.id=asg.userid
AND context.instanceid=course.id
Output of first stament:
Firstname Lastname Email Course Role
John Doe john.doe#email.com Course-Name Student
Second statement:
SELECT user.firstname AS 'First Name', user.lastname AS 'Last Name', user.email AS 'Email', user_info_data.data AS 'IBCLC Certified'
FROM user, user_info_data
WHERE user.id = user_info_data.userid
AND fieldid = '15'
Output of second stament:
Firstname Lastname Email IBCLC Certified
John Doe john.doe#email.com Yes
Desired Output:
FirstName,LastName,Email,IBCLC Certified,Course,Role
Other select statement I tried: Brings up 9,494 records, but right now the field data where fieldid is 15 is a list of possible choices, could that be why?
SELECT user.firstname AS Firstname, user.lastname AS Lastname, user.email AS Email, userdata.data, course.fullname AS Course, role.name AS Role
FROM user AS user, course AS course, user_info_data AS userdata, role,role_assignments AS asg
INNER JOIN context AS context ON asg.contextid=context.id
WHERE context.contextlevel = 50
AND userdata.fieldid = 15
AND role.id=asg.roleid
AND user.id=asg.userid
AND context.instanceid=course.id
I added user_info_data to your first request like this:
SELECT user.firstname AS Firstname,
user.lastname AS Lastname,
user.email AS Email,
course.fullname AS Course,
role.name AS Role,
ibclcCert.data AS 'IBCLC Certified'
FROM user,
course,
role,
role_assignments AS asg,
context,
user_info_data AS ibclcCert
WHERE context.contextlevel = 50
AND role.id=asg.roleid
AND user.id=asg.userid
AND context.instanceid=course.id
AND asg.contextid=context.id
AND ibclcCert.userid = user.id
AND ibclcCert.fieldid = '15'
I renamed the user_info_data table reference to something denoting the actual field, ibclcCert in this case. This renaming is a provision in case that you one day want to access more than one data field. When you do, you'd include the table multiple times, one for every field you need. See also this answer about how to deal with such data formats.