Use same column in a SQL Query twice - mysql

I'm writing sql query where I want to use the same column twice in datagrid view.
Here is my query:
SELECT ElectricityMachinePanelDetails.MachineDescription AS "Machine Name",
ReadingValue AS "Last Day Meter Reading"
FROM ElectricityDailyMeterReadingDetails
INNER JOIN ElectricityMachinePanelDetails ON ElectricityMachinePanelDetails.MachinePanelID = ElectricityDailyMeterReadingDetails.MachinePanelID
INNER JOIN ReadingTypesDetails ON ElectricityDailyMeterReadingDetails.ReadingTypeID = ReadingTypesDetails.ReadingTypeID
WHERE ReadingCategoryID = 'RC001' AND
ReadingTypesDetails.ReadingTypeID = 'RT001'
How can I use column name ReadingValue twice in the datagrid.

First of all, use aliases instead of table names in joins. So your query could be more readable.
select
empd.MachineDescription as "Machine Name",
rtd.ReadingValue AS "Last Day Meter Reading"
from ElectricityDailyMeterReadingDetails as edmrd
inner join ElectricityMachinePanelDetails as empd on empd.MachinePanelID = edmrd.MachinePanelID
inner join ReadingTypesDetails as rtd on rtd.ReadingTypeID = edmrd.ReadingTypeID
where
rtd.ReadingCategoryID = 'RC001' and
rtd.ReadingTypesDetails.ReadingTypeID = 'RT001'
If you want to join ReadingTypesDetails twice, you can easily do this:
select
empd.MachineDescription as "Machine Name",
rtd.ReadingValue as "Last Day Meter Reading",
rtd2.ReadingValue as "Another Reading"
from ElectricityDailyMeterReadingDetails as edmrd
inner join ElectricityMachinePanelDetails as empd on empd.MachinePanelID = edmrd.MachinePanelID
inner join ReadingTypesDetails as rtd on rtd.ReadingTypeID = edmrd.ReadingTypeID
inner join ReadingTypesDetails as rtd2 on rtd2.ReadingTypeID = edmrd.ReadingTypeID
where
rtd.ReadingCategoryID = 'RC001' and
rtd.ReadingTypesDetails.ReadingTypeID = 'RT001' and
--rtd2.ReadingCategoryID = '????' and
--rtd2.ReadingTypesDetails.ReadingTypeID = '????' and

You could just use it twice, if the datagridview allows doublename im not sure. Otherwise just give it another name "Last Day Meter Reading Copy".
Select
ElectricityMachinePanelDetails.MachineDescription AS "Machine Name",
ReadingValue AS "Last Day Meter Reading",
ReadingValue AS "Last Day Meter Copy"
from ElectricityDailyMeterReadingDetails
INNER JOIN ElectricityMachinePanelDetails on ElectricityMachinePanelDetails.MachinePanelID = ElectricityDailyMeterReadingDetails.MachinePanelID
INNER JOIN ReadingTypesDetails ON ElectricityDailyMeterReadingDetails.ReadingTypeID = ReadingTypesDetails.ReadingTypeID where ReadingCategoryID = 'RC001' AND ReadingTypesDetails.ReadingTypeID = 'RT001'
In MSSQL you cannot have the same column name twice i think. But in MySQL its fine.

Related

SSRS: Custom parameter layout was removed from the report

When I add a parameter to my report, add it to the query and used it in a calculated field, running the report gives me this error:
"Custom parameter layout was removed from the report. SQL Server 2014
Reporting Services and earlier do not support custom parameter
layout."
My report runs but returns no rows, just column headers.
My parameter is of type Date/Time
My query is:
SELECT HD_QUEUE.NAME as qname, HD_TICKET.ID, HD_TICKET.CREATED, HD_TICKET.TIME_CLOSED, CUSTOMER.FULL_NAME as custfullname,
HD_STATUS.NAME as statname, HD_TICKET.TITLE, left(ASSIGNEE.FULL_NAME, 40) as assignee,
HD_PRIORITY.NAME as pname, HD_CATEGORY.NAME as catname
FROM HD_TICKET
INNER JOIN HD_QUEUE
ON HD_TICKET.HD_QUEUE_ID = HD_QUEUE.ID
INNER JOIN USER CUSTOMER
ON HD_TICKET.SUBMITTER_ID=CUSTOMER.ID
INNER JOIN USER ASSIGNEE
ON HD_TICKET.OWNER_ID=ASSIGNEE.ID
INNER JOIN HD_STATUS
ON (HD_TICKET.HD_STATUS_ID=HD_STATUS.ID)
AND (HD_TICKET.HD_QUEUE_ID=HD_STATUS.HD_QUEUE_ID)
INNER JOIN HD_PRIORITY
ON HD_TICKET.HD_PRIORITY_ID = HD_PRIORITY.ID
and HD_TICKET.HD_QUEUE_ID = HD_PRIORITY.HD_QUEUE_ID
INNER JOIN HD_CATEGORY
ON HD_TICKET.HD_CATEGORY_ID = HD_CATEGORY.ID
and HD_TICKET.HD_QUEUE_ID = HD_CATEGORY.HD_QUEUE_ID
left join ASSET on ASSET.ID = HD_TICKET.ASSET_ID
left join ASSET_DATA_6 on ASSET.ASSET_DATA_ID = ASSET_DATA_6.ID
WHERE HD_STATUS.NAME = 'Closed'
AND HD_TICKET.TIME_CLOSED > DATE_SUB(#date_param, INTERVAL 34 DAY)
AND HD_TICKET.TIME_CLOSED <= #date_param;
And my calculated field is:
=IIf(Fields!closed_date.Value > (DateAdd(DateInterval.Day, -6, Parameters!date_param.Value)), "Week 1",
IIf(Fields!closed_date.Value > (DateAdd(DateInterval.Day, -13, Parameters!date_param.Value)), "Week 2",
IIf(Fields!closed_date.Value > (DateAdd(DateInterval.Day, -20, Parameters!date_param.Value)), "Week 3",
IIf(Fields!closed_date.Value > (DateAdd(DateInterval.Day, -27, Parameters!date_param.Value)), "Week 4",
"Week 5"))))

Selecting multiple rows in same table in the same JOIN

In the picture is my table situation right now:
The central table in this case right now is tblJob, here is everything defined what I need (not all in the picture).
The address table needs to return 2 values (1 of the company and 1 of the job itself). The only thing I need to do right now is to add the company address (the job address is already in my query) My query already looks like this:
SELECT
tblJob.jobID,
tblJob.amount AS jobAmount,
tblJob.extraInfo AS jobExtraInfo,
tblJob.views AS jobViews,
tblJob.description AS jobDescription,
tblJob.dateCreated AS jobDateCreated,
tblJobFunction.jobFunctionID,
tblJobFunction.jobFunction,
tblAddress.zipcode AS jobAddress,
tblAddress.city AS jobCity,
tblAddress.street AS jobStreet,
tblAddress.number AS jobNumber,
tblAddress.bus AS jobBus,
tblCountry.countryID AS jobCountryID,
tblCountry.country AS jobCountry,
tblCountry.areaCode AS jobAreaCode,
tblCompany.companyID,
tblCompany.name,
tblCompany.email,
tblCompany.GSM,
tblCompany.phoneNumber,
tblCompany.photoURL AS companyPhotoURL,
tblCompany.VATNumber,
tblCompany.websiteURL,
tblEvent.eventID,
tblEvent.event,
tblEvent.description AS eventDescription,
tblEvent.startDate AS eventStartDate,
tblEvent.endDate AS eventEndDate,
tblEvent.facebookURL,
tblEvent.photoURL AS eventPhotoURL,
tblEvent.views AS eventViews,
tblEvent.dateCreated AS eventDateCreated
FROM tblJob
JOIN tblAddress ON tblAddress.addressID = tblJob.addressID
JOIN tblCountry ON tblAddress.countryID = tblCountry.countryID
JOIN tblJobFunction ON tblJob.jobFunctionID =
tblJobFunction.jobFunctionID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID
LEFT JOIN tblEvent ON tblJob.eventID = tblEvent.eventID
Now the question is: how can I add the address from the company in the same query?
Use the address table as many times as you need it, but each time you must give it a new alias:
FROM tblJob
JOIN tblAddress ON tblAddress.addressID = tblJob.addressID
JOIN tblCountry ON tblAddress.countryID = tblCountry.countryID
JOIN tblJobFunction ON tblJob.jobFunctionID = tblJobFunction.jobFunctionID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID
JOIN tblAddress a2 ON a2.addressID = tblCompany.addressID
LEFT JOIN tblEvent ON tblJob.eventID = tblEvent.eventID
perhaps more like this:
SELECT JobAddress.street, CompanyAddress.street
FROM tblJob
JOIN tblAddress JobAddress ON JobAddress.addressID = tblJob.addressID
JOIN tblCompany ON tblJob.companyID = tblCompany.companyID
JOIN tblAddress CompanyAddress ON CompanyAddress.addressID = tblCompany.addressID

sub-select query in SQL will not populated new column/field with specific text

How do I get my new field to populate with Yes or No rather than pre-existing data? In this case, I'm getting a new field called ESL but I can only get it to run if i populated the field with colleagueId. I want it to populate with Yes and not true with No. I've also tried case statements.
select distinct s.colleagueId, st.enrollmentStatus,
s.firstEnrolledTerm, ESL.colleagueId as ESL
from tbl_studentTerms st
left join
(select distinct colleagueId
from tbl_studentclasses
where enrolled = 1
and subject = 'ESL') as ESL
on ESL.colleagueId=st.colleagueId
inner join tbl_students s
on st.colleagueId = s.colleagueId
where s.endingCohort = '2009SP'
and st.term='2009SP'
and s.colleagueId in(select [Student ID] from dbo.pvt_SelectedStudents)
Here is one method:
select distinct s.colleagueId, st.enrollmentStatus,
s.firstEnrolledTerm,
coalesce(ESL.ESL, 'No') as ESL
from tbl_studentTerms st inner join
tbl_students s
on st.colleagueId = s.colleagueId left join
(select distinct colleagueId, 'Yes' as ESL
from tbl_studentclasses
where enrolled = 1 and subject = 'ESL'
) ESL
on ESL.colleagueId = st.colleagueId
where s.endingCohort = '2009SP' and st.term = '2009SP' and
s.colleagueId in (select [Student ID] from dbo.pvt_SelectedStudents);
Notes:
I move the inner join to be before the left join. I find it easiest to read query where inner joins come first, followed by left joins.
Do not use select distinct unless you really need to remove duplicates.

Search a table based on multiple rows in another table

Basically I have three MySQL tables:
Users - contains base information on users
Fields - describes additional fields for said users (e.g. location, dob etc.)
Data - Contains user data described via links to the fields table
With the basic design as follows (the below is a stripped down version)
Users:
ID | username | password | email | registered_date
Fields
ID | name | type
Data:
ID | User_ID | Field_ID | value
what I want to do is search Users by the values for the fields they have, e.g. example fields might be:
Full Name
Town/City
Postcode
etc.
I've got the following, which works when you're only wanting to search by one field:
SELECT `users`.`ID`,
`users`.`username`,
`users`.`email`,
`data`.`value`,
`fields`.`name`
FROM `users`,
`fields`,
`data`
WHERE `data`.`Field_ID` = '2'
AND `data`.`value` LIKE 'london'
AND `users`.`ID` = `data`.`User_ID`
AND `data`.`Field_ID` = `fields`.`ID`
GROUP BY `users`.`ID`
But what about if you want to search for Multiple fields? e.g. say I want to search for Full Name "Joe Bloggs" With Town/City set to "London"? This is the real sticking point for me.
Is something like this possible with MySQL?
I'm going with the assumption that "searching multiple fields" is talking about the Entity-Attribute-Value structure.
In that case, I propose that the first step is to create a derived query - basically, we want to limit the "EAV data joined" to only include the records that have the values we are interested in finding. (I've altered some column names, but the same premise holds.)
SELECT d.userId
FROM data d
JOIN fields f
ON f.fieldId = d.fieldId
-- now that we establish data/field relation, filter rows
WHERE f.type = "location" AND d.value = "london"
OR f.type = "job" AND d.value = "programmer"
This resulting rows are derived from the filtered EAV triplets that match our conditions. Only the userId is selected in this case (as it will be used to join against the user relation), but it is also possible to push fieldId/value/etc through.
Then we can use all of this as a derived query:
SELECT *
FROM users u
JOIN (
-- look, just goes in here :)
SELECT DISTINCT d.userId
FROM data d
JOIN fields f
ON f.fieldId = d.fieldId
WHERE f.type = "location" AND d.value = "london"
OR f.type = "job" AND d.value = "programmer"
) AS e
ON e.userId = u.userId
Notes:
The query planner will figure all the RA stuff out peachy keen; don't worry about this "nesting" as there is no dependent subquery.
I avoid the use of implicit cross-joins as I feel they muddle most queries, this case being a particularly good example.
I've "cheated" and added a DISTINCT to the derived query. This will ensure that at most one record will be joined/returned per user and avoids the use of GROUP BY.
While the above gets "OR" semantics well (it's both easier and I may have misread the question), modifications are required to get "AND" semantics. Here are some ways that the derived query can be written to get such. (And at this point I must apologize to Tony - I forget that I've already done all the plumbing to generate such queries trivially in my environment.)
Count the number of matches to ensure that all rows match. This will only work if each entity is unique per user. It also eliminates the need for DISTINCT to maintain correct multiplicity.
SELECT d.userId
FROM data d
JOIN fields f
ON f.fieldId = d.fieldId
-- now that we establish data/field relation, filter rows
WHERE f.type = "location" AND d.value = "london"
OR f.type = "job" AND d.value = "programmer"
GROUP BY d.userId
HAVING COUNT(*) = 2
Find the intersecting matches:
SELECT d.userId
FROM data d
JOIN fields f ON f.fieldId = d.fieldId
WHERE f.type = "location" AND d.value = "london"
INTERSECT
SELECT d.userId
FROM data d
JOIN fields f ON f.fieldId = d.fieldId
WHERE f.type = "job" AND d.value = "programmer"
Using JOINS (see Tony's answer).
SELECT d1.userId
FROM data d1
JOIN data d2 ON d2.userId = d1.userId
JOIN fields f1 ON f1.fieldId = d1.fieldId
JOIN fields f2 ON f2.fieldId = d2.fieldId
-- requires AND here across row
WHERE f1.type = "location" AND d1.value = "london"
AND f2.type = "job" AND d2.value = "programmer"
An inner JOIN itself provides conjunction semantics when applied outside of the condition. In this case I show "re-normalize" the data. This can also be written such that [sub-]selects appear in the select clause.
SELECT userId
FROM (
-- renormalize, many SO questions on this
SELECT q1.userId, q1.value as location, q2.value as job
FROM (SELECT d.userId, d.value
FROM data d
JOIN fields f ON f.fieldId = d.fieldId
WHERE f.type = "location") AS q1
JOIN (SELECT d.userId, d.value
FROM data d
JOIN fields f ON f.fieldId = d.fieldId
WHERE f.type = "job") AS q2
ON q1.userId = q2.userId
) AS q
WHERE location = "london"
AND job = "programmer"
The above duplicity is relatively easy to generate via code and some databases (such as SQL Server) support CTEs which make writing such much simpler. YMMV.
If I understood you right, this is what you want:
FROM `users`,
`fields`,
`data` `location`
`data` `name`
WHERE `location`.`Field_ID` = '2'
AND `location`.`value` LIKE 'london'
AND `location`.`Field_ID` = `fields`.`ID`
AND `name`.`Field_ID` = 'whathere? something for its name'
AND `name`.`value` LIKE 'london'
AND `name`.`Field_ID` = `fields`.`ID`
AND `users`.`ID` = `data`.`User_ID`
I'd prefer joins though
Well here you hit one of the downsides of the EAV you are using
SELECT u.ID, u.username,u.email, d1.value, f1.Name, d2.Value, f2.name
FROM `users` u,
inner join data d1 On d1.User_id = u.id
inner join data d2 On d2.User_id = u.id
inner join fields f1 on f1.id = d1.field_id
inner join fields f2 on f2.id = d2.field_id
WHERE d1.Field_id = '2' and d1.Value = 'london'
and d2.field_id = '??' and d2.value = 'Joe Bloggs'
GROUP BY `users`.`ID`
Messy isn't it? Bet you can't wait to go for, four or five values. Or think about (Forename = Joe Or surname = Bloggs) and City = London...

Referencing (Using an alias) the value from nested MySQL query in an outer conditional statement

I'm using a nested query to get the value I need from a table that I then need to use in a conditional statement, however, every time I try this I keep on getting an error saying unknown column (format) in the field list
SELECT
(SELECT format FROM competition_stages WHERE comp_id = "5" AND rid = "24") AS format,
a.tie_id, b.name AS team_a, b.team_id AS team_a_id, c.name AS team_b, c.team_id AS team_b_id, SUM(e.bonus) AS team_a_bonus, SUM(f.bonus) AS team_b_bonus,
SUM(CASE
WHEN (a.team_a = e.team_id AND format = "0") THEN e.score
END) as team_a_agg,
SUM(CASE
WHEN (a.team_b = f.team_id AND format = "0") THEN f.score
END) as team_b_agg
FROM competition_tie a
INNER JOIN teams b ON (a.team_a = b.team_id)
INNER JOIN teams c ON (a.team_b = c.team_id)
LEFT JOIN fixtures d ON (a.tie_id = d.tie_id)
LEFT JOIN fixture_scores e ON (d.fx_id = e.fx_id AND a.team_a = e.team_id)
LEFT JOIN fixture_scores f ON (d.fx_id = f.fx_id AND a.team_b = f.team_id)
WHERE a.comp_id = "5" AND a.rid = "24" AND a.season_id = "5"
GROUP BY a.tie_id
ORDER BY a.tie_id ASC
I can get the value of the format column in my results when I go through them but it just seems I can't use it within my query to use in.
Thanks for your help!
Instead of using a subquery, simply join the competition_stages table to your query so that you can reference the format column directly. Assuming there is no appearant relation between the competition_stages table and the other tables in the query (at least not from the information on hand), you can just join the table using the two conditions you specified if these conditions would only yield 1 result in the competition_stages table. Something like this:
SELECT cs.format, a.tie_id, ....
FROM competition_tie a ...
INNER JOIN competition_stages cs ON cs.comp_id = "5" AND cs.rid = "24"