Get 3 column left join based on same one table - mysql

I have 3 column here in tblItem
purchase
stock
calculate
and this 3 column have to join with tblMeasurement
name
I have tried this, but when I display 3 columns show the same all.
SQL
$sql = "SELECT A.itemID, A.categoryID, A.purchaseMeasurementID, A.stockMeasurementID, A.calculationMeasurementID, A.itemName, B.itemCategoryName, C.measurementName
FROM tblPurItem A
LEFT JOIN tblPurItemCategory B
ON A.categoryID = B.itemcategoryID
LEFT JOIN tblPurMeasurement C
ON A.purchaseMeasurementID= C.measurementID";
As you see my sql above, it has join only for purchaseMeasurementID. How do I join stockMeasurementID and calculationMeasurementID based on also tblPurMeasurement ? Is there any missing here?

Try using this subquery instead.
SELECT A.itemID, A.categoryID, A.purchaseMeasurementID, A.stockMeasurementID, A.calculationMeasurementID, A.itemName
, (select B.itemCategoryName from tblPurItemCategory B where A.categoryID = B.itemcategoryID limit 1) as itemCategoryName
, (select C.measurementName from tblPurMeasurement C where A.purchaseMeasurementID= C.measurementID limit 1) as purchasemeasurementName
, (select C.measurementName from tblPurMeasurement C where A.stockMeasurementID= C.measurementID limit 1) as stockmeasurementName
, (select C.measurementName from tblPurMeasurement C where A.calculationMeasurementID= C.measurementID limit 1) as calculationmeasurementName
FROM tblPurItem A

Related

Combine data with same id in one column

I have this problem. I need to combine data with the same id in one column. The data are separated with ','. I use group_concat but the result is that it combines all. What I need is for example:
But the result is:
my code
SELECT A.bookId,A.bookDate, A.serviceDate, A.bookTime,A.status, GROUP_CONCAT(C.serviceItemId
SEPARATOR ',') AS Servis, B.custId, B.custFname, B.custLname,B.custContact, B.custEmail, B.gender
FROM booking A
JOIN booking_service C on A.bookId = C.bookId
JOIN customer B ON B.custId =
A.cust_fk WHERE A.cust_fk = 4
ORDER BY A.bookId
Can someone help me?
Why not group_concat the values in a sub-query and then join it to your main result set:
SELECT A.bookId,
A.bookDate,
A.serviceDate,
A.bookTime,
A.status,
d.Servis,
B.custId,
B.custFname,
B.custLname,
B.custContact,
B.custEmail,
B.gender
FROM (
SELECT bookId,
GROUP_CONCAT(serviceItemId SEPARATOR ',') AS Servis
FROM booking_service
GROUP BY bookId
) d
JOIN booking A ON a.bookID = d.bookID
JOIN booking_service C on A.bookId = C.bookId
JOIN customer B ON B.custId = A.cust_fk WHERE A.cust_fk = 4
ORDER BY A.bookId
You need to use GROUP BY with GROUP_CONCAT if you want to limit the results to, for example, a single bookId.

bring the last 10 orders whitout repeating

I have the following query
SELECT a.id, a.fecha, a.ser, a.numero, c.nombre_apellido, a.estado, a.tipo, a.articulo, a.precio_asignado, a.retirada, a.pronta, a.precio, a.confirmada, d.marca, a.modelo, a.fecha_prometido, a.fecha_asignado, a.presupuesto, a.cant_llamados
FROM (
(
(
ordenes_servicio_bitacora b
LEFT JOIN ordenes_reparaciones a ON b.id_orden = a.id
)
LEFT JOIN clientes c ON a.cliente_id = c.id
)
LEFT JOIN marcas d ON a.marca_id = d.id
)
ORDER BY b.id_bitacora DESC
LIMIT 10
and it brings me this
as you see the id column of the order is repeated because of the cross with bitacora table i need not to be repeated, any ideas? Thanks in advance.
DISTINCT should do the job in your case, as all the columns' data are repeated for the row not just the id column:
SELECT DISTINCT
a.id, a.fecha, a.ser, a.numero,
c.nombre_apellido, a.estado,
a.tipo, a.articulo, a.precio_asignado,
a.retirada, a.pronta, a.precio,
a.confirmada, d.marca, a.modelo,
a.fecha_prometido, a.fecha_asignado,
a.presupuesto, a.cant_llamados
FROM ordenes_servicio_bitacora b
LEFT JOIN ordenes_reparaciones a ON b.id_orden = a.id
LEFT JOIN clientes c ON a.cliente_id = c.id
LEFT JOIN marcas d ON a.marca_id = d.id
ORDER BY b.id_bitacora DESC
LIMIT 10
SELECT a.id, a.fecha, a.ser, a.numero, c.nombre_apellido, a.estado, a.tipo, a.articulo, a.precio_asignado, a.retirada, a.pronta, a.precio, a.confirmada, d.marca, a.modelo, a.fecha_prometido, a.fecha_asignado, a.presupuesto, a.cant_llamados
FROM (
(
(
(SELECT DISTINCT id_orden
FROM `ordenes_servicio_bitacora`
ORDER BY id_bitacora DESC
LIMIT 10) b
LEFT JOIN ordenes_reparaciones a ON b.id_orden = a.id
)
LEFT JOIN clientes c ON a.cliente_id = c.id
)
LEFT JOIN marcas d ON a.marca_id = d.id
)
i just made a subquery and the job is done, thanks by the answers and comments :)

How to deduct in group by query in sum in access

I have query like this ::
SELECT account.AccountNumber, account.NAME, Sum(agro.price * agro.qty) AS Expr1
FROM ((account
INNER JOIN data ON account.AccountNumber = data.acno)
INNER JOIN agro ON agro.BillNo = data.BillNo)
WHERE data.db='true'
GROUP BY account.AccountNumber, account.NAME;
I want to deduct another groupby query output in to Sum(agro.price * agro.qty) this
the another group by query is SELECT Sum(rs),acno
FROM jma group by acno;
i want to deduct Sum(agro.price * agro.qty)-Sum(rs) how its work please help me solve this
If I am understanding you correctly the following query may work for you:
SELECT subQ.AccountNumber, subQ.NAME, (subQ.subSum - jmaSum.jSum) AS FinalSum
FROM
(
SELECT a.AccountNumber, a.NAME, Sum(ag.price * ag.qty) AS subSum
FROM (account AS a
INNER JOIN data AS d ON a.AccountNumber = d.acno)
INNER JOIN agro AS ag ON ag.BillNo = d.BillNo
WHERE d.db = 'true'
GROUP BY a.AccountNumber, a.NAME
) AS subQ
LEFT JOIN
(
SELECT Sum(j.rs) AS jSum, j.acno
FROM jma AS j
GROUP BY j.acno
) AS jmaSum ON subQ.AccountNumber = jmaSum.acno

Trying to add one last SUM() column to my query in SQL Server 2008

I have the first query which is producing correct results. What I need is I need to add the sum of values as a last column grouped by surveyid. I can't insert Sum(c.value) into the first query because it is an aggregate function. I have the correct query as my second query below. I know there's pivot functionality but not sure if it can be used here. I do realize that there will be repetition but that's okay.
'first query
SELECT
A.PATIENTID, B.STUDENTNUMBER, c.surveyid,
convert(varchar, A.CreatedDate, 107),
C.QuestionID, C.Value, D.Question
FROM
dbo.Survey A, dbo.Patient B, [dbo].[SurveyQuestionAnswer] C, [dbo].[LookupQuestions] D
WHERE
A.PATIENTID = B.ID
and c.SurveyID = A.ID
and c.QuestionID = d.ID
and c.questionid <> 10
ORDER BY
A.PATIENTID
'second query
select
c.surveyid,SUM(c.value) as scores
from
dbo.SurveyQuestionAnswer c
group by
c.SurveyID
order by
SurveyID '---not important
You can use SUM if you add the OVER clause. In this case:
SELECT
A.PATIENTID, B.STUDENTNUMBER, c.surveyid,
convert(varchar, A.CreatedDate, 107),
C.QuestionID, C.Value, D.Question,
SUM(c.Value) OVER(PARTITION BY c.surveyid) scores
FROM
dbo.Survey A
INNER JOIN dbo.Patient B
ON A.PATIENTID = B.ID
INNER JOIN [dbo].[SurveyQuestionAnswer] C
ON c.SurveyID = A.ID
INNER JOIN [dbo].[LookupQuestions] D
ON c.QuestionID = d.ID
WHERE
c.questionid <> 10
ORDER BY
A.PATIENTID
You could use something like this:
SELECT
s.PATIENTID, p.STUDENTNUMBER, sqa.surveyid,
CONVERT(varchar, s.CreatedDate, 107),
sqa.QuestionID, sqa.Value, lq.Question,
Scores = (SELECT SUM(Value) FROM dbo.SurveyQuestionAnswer s2 WHERE s2.SurveyID = s.ID)
FROM
dbo.Survey s
INNER JOIN
dbo.Patient p ON s.PatientID = p.ID
INNER JOIN
[dbo].[SurveyQuestionAnswer] sqa ON sqa.SurveyID = s.ID
INNER JOIN
[dbo].[LookupQuestions] lq ON sqa.QuestionID = lq.ID
WHERE
sqa.questionid <> 10
ORDER BY
s.PATIENTID
By having a subquery with the SUM(...) you should be able to get that sum as a single value and you don't need to use any grouping function

How to write a select statement inside another select in SQL

Can anyone tell me what is wrong with this query?
it gives a syntax error near the 2nd select
SELECT b.mc_boxes_idmc_boxes,
t.idtitles,
t.title,
t.languages_idlanguages,
MAX(h.idtitle_history),
MAX(h.edition)
(SELECT h.preview, h.file WHERE h.idtitle_history = MAX(h.idtitle_history))
FROM mc_boxes_has_titles b
LEFT JOIN titles t ON b.titles_idtitles = t.idtitles
LEFT JOIN title_history h ON h.titles_idtitles = t.idtitles
WHERE b.mc_boxes_idmc_boxes = 12
AND h.edition IS NOT NULL
GROUP BY b.mc_boxes_idmc_boxes, idtitles
ORDER BY b.sortorder;
looks like you are missing a comma after MAX(h.edition)
SELECT b.mc_boxes_idmc_boxes,
t.idtitles,
t.title,
t.languages_idlanguages,
MAX(h.idtitle_history),
MAX(h.edition),
(SELECT h.preview, h.file WHERE h.idtitle_history = MAX(h.idtitle_history))
FROM mc_boxes_has_titles b
LEFT JOIN titles t ON b.titles_idtitles = t.idtitles
LEFT JOIN title_history h ON h.titles_idtitles = t.idtitles
WHERE b.mc_boxes_idmc_boxes = 12
AND h.edition IS NOT NULL
GROUP BY b.mc_boxes_idmc_boxes, idtitles
ORDER BY b.sortorder;
besides the comma, you are selecting two fields in your subquery
SELECT b.mc_boxes_idmc_boxes,
t.idtitles,
t.title,
t.languages_idlanguages,
MAX(h.idtitle_history),
MAX(h.edition),
(SELECT preview FROM title_history WHERE idtitle_history = MAX(h.idtitle_history)),
(SELECT [file] FROM title_history WHERE idtitle_history = MAX(h.idtitle_history))
FROM mc_boxes_has_titles b
LEFT JOIN titles t ON b.titles_idtitles = t.idtitles
LEFT JOIN title_history h ON h.titles_idtitles = t.idtitles
WHERE b.mc_boxes_idmc_boxes = 12
AND h.edition IS NOT NULL
GROUP BY b.mc_boxes_idmc_boxes, idtitles
ORDER BY b.sortorder;
Adding to bluefeet's answer, you may want to check for reserved words. "File" for example is a reserved word in sql server.
Alias it as a virtual table. Change something like
SELECT b.mc_boxes_idmc_boxes,
t.idtitles,
t.title,
t.languages_idlanguages,
MAX(h.idtitle_history),
MAX(h.edition)
(SELECT h.preview, h.file WHERE h.idtitle_history = MAX(h.idtitle_history))
FROM mc_boxes_has_titles b
LEFT JOIN titles t ON b.titles_idtitles = t.idtitles
LEFT JOIN title_history h ON h.titles_idtitles = t.idtitles
WHERE b.mc_boxes_idmc_boxes = 12
AND h.edition IS NOT NULL
GROUP BY b.mc_boxes_idmc_boxes, idtitles
ORDER BY b.sortorder) as virtual_column_alias;
Check this out. Hope this will work.