MYSQL, grouping with multiple columns - mysql

I have two tables. Sample Data Query:
cmadjprice:
select symbol,close,timestamp from cmadjprice;
ABCD,815.9,2014-10-31
ABCD,808.85,2014-11-03
ABCD,797.4,2014-11-05
ABCD,776.55,2014-11-07
ABCD,800.85,2014-11-10
ABCD,808.9,2014-11-11
ABCD,826.8,2014-11-12
ABCD,856.45,2014-11-13
ABCD,856.65,2014-11-14
BB03 table output sample query
select symbol,enter_dt,enter_price,exit_dt,exit_price from bb03 ;
ABCD,2014-10-31,815.90,2018-07-27,1073.60
am looking for maximum closing price with same date.
select a.symbol, max(a.close) ,a.timestamp from cmadjprice a
inner join BB03 b on a.symbol = b.symbol
where a.timestamp between b.enter_dt and b.exit_dt
group by a.symbol,a.timestamp;
am not getting output? Please help on this
Expecting output
ABCD,2014-10-31,815.90,2018-07-27,1073.60,856.65,2014-11-14;

I think this is what you need:
Note that this may return more than one record in case if the maximum close value appeared more than once throughout the sequence of timestamps related to a given symbol
select c.symbol, c.maxval, d.timestamp from
(
select
a.symbol,
max(a.close) as maxval
from
cmadjprice a
inner join BB03 b
on a.symbol = b.symbol
where a.timestamp between b.enter_dt and b.exit_dt
group by a.symbol
) c
inner join
cmadjprice d
on c.symbol = d.symbol and c.maxval = d.close
;

Try below :
select a.symbol, max(cast(a.close as DECIMAL(5,2))) from cmadjprice a
inner join BB03 b on a.symbol = b.symbol
where a.timestamp between b.enter_dt and b.exit_dt
group by a.symbol;

Related

Delete a Select Inner Join Query result

SELECT yturl from ytpointadder a
JOIN watched b on b.watchedyt = a.yturl AND b.ip = a.ip
Group by a.ip;
I want to delete the result of the query for exp this query result is :
yturl
ip
id
eY5WRONGXDI
197.XX.XX.XXX
1
Though i want to delete it from ytpointadder. I tried :
DELETE from ytpointadder a
JOIN watched b on b.watchedyt = a.yturl AND b.ip = a.ip
Group by a.ip;
You can't specify same target table for update (delete) in FROM clause. So you have to use another outer query.
Try:
DELETE FROM ytpointadder
WHERE yturl IN ( SELECT t.yturl FROM (SELECT a.yturl, a.ip from ytpointadder a
JOIN watched b on b.watchedyt = a.yturl AND b.ip = a.ip
Group by a.ip
) as t
) ;
In a partial query, it should return one column
You may need to use parentheses
try this
DELETE FROM ytpointadder
WHERE yturl IN
(
SELECT a.yturl from ytpointadder a
JOIN watched b on b.watchedyt = a.yturl AND b.ip = a.ip
Group by a.ip)

Get 3 column left join based on same one table

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

Sql trouble with coalesce() not working propely

i have a query and i'm having trouble to change the name of the last row of columb name to 'TOTAL'. The result gives me the same name of the row above the last row.
Here's my query:
SELECT COALESCE(ticket_types.name,'TOTAL') AS name,
COUNT(1) AS quantity
FROM tr_logs
LEFT JOIN tickets ON tr_logs.value = tickets.id
LEFT JOIN ticket_types ON tickets.ticket_type_id = ticket_types.id
LEFT JOIN transactions ON tr_logs.transaction_id = transactions.id
LEFT JOIN tr_fields_data AS tfd_shipping ON tfd_shipping.transaction_id = transactions.id
WHERE type = 'ADDITEM'
AND transactions.event_id = '46'
AND DATE(tr_logs.created_date)
BETWEEN '2017-03-26' AND '2017-05-24'
AND tfd_shipping.data IN ('0','570','571','771')
AND name IS NOT NULL
GROUP BY ticket_types.id WITH ROLLUP
The result looks like this:
name quantity
premium 56
outlaw 6
outlaw 62
Last row name from rollup is not null.... I need it to be TOTAL and not outlaw
Thanks
You haven't changed the name to TOTAL at all: you've changed the name of the column to name, and you've told it to replace any null values with TOTAL.
If you want to change the name of ticket_types.name to total, you just want
SELECT ticket_types.name AS total ...
(But it would be weird to rename something called name to total, so perhaps you need to clarify your requirements a little.)
This may or not be related to your observed problem, but the WHERE and GROUP BY clauses turn all the outer joins into inner joins. You should simplify the query to:
SELECT COALESCE(tt.name, 'TOTAL') AS name, COUNT(1) AS quantity
FROM tr_logs l JOIN
tickets
ON l.value = t.id JOIN
ticket_types tt
ON t.ticket_type_id = tt.id JOIN
transactions tr
ON l.transaction_id = tr.id JOIN
tr_fields_data fd
ON fd.transaction_id = tr.id
WHERE type = 'ADDITEM' AND
tr.event_id = '46' AND
DATE(l.created_date) BETWEEN '2017-03-26' AND '2017-05-24' AND
fd.data IN ('0', '570', '571', '771') AND
tt.name IS NOT NULL
GROUP BY tt.id WITH ROLLUP
Thanks to Gordon Linoff I have figure out my problem.
The name of the last row was never null beacause i GROUP BY with a different attribute.
Here's the solution.
SELECT COALESCE(tckn,'TOTAL') AS name, quantity FROM
(SELECT tt.name AS tckn, COUNT(1) AS quantity
FROM tr_logs AS l
LEFT JOIN tickets AS t ON l.value = t.id
LEFT JOIN ticket_types AS tt ON t.ticket_type_id = tt.id
LEFT JOIN transactions AS tr ON l.transaction_id = tr.id
LEFT JOIN tr_fields_data AS tfd ON tfd.transaction_id = tr.id
WHERE type = 'ADDITEM'
AND tr.event_id = '46'
AND DATE(l.created_date)
BETWEEN '2017-03-26' AND '2017-05-24'
AND tfd.data IN ('0','570','571','771')
GROUP BY tckn WITH ROLLUP) as sum;

Count invitation response against events and response codes

I have this table for Response Codes:
And this table for invitations:
My query so far gives this:
While I want to achieve this:
MY QUERY:
SELECT
i.eventId
,code.responseCode
,COUNT(i.attendeeResponse) responseCount
FROM invitations i
LEFT JOIN response_codes code
ON code.responseCode = i.attendeeResponse
GROUP BY i.eventId, code.responseCode, i.attendeeResponse;
SQLFiddle
You need to construct a cartesian product of all eventIds and responseCodes at first (you can achieve it with join without condition):
select c.eventId
, c.responseCode
, count( i.attendeeResponse ) as responseCount
from ( select distinct t1.responseCode
, t2.eventId
from `response_codes` t1
join `invitations` t2 ) c
left join `invitations` i on c.responseCode = i.attendeeResponse and c.eventId = i.eventId
group by c.eventId, c.responseCode;
SQLFiddle
You need to cross join the responsecode table to get the all combinations of eventid and responsecode.
SQL Fiddle
SELECT distinct
i.eventId
,code.responseCode
,case when t.responseCount is null then 0
else t.responsecount end rcount
FROM invitations i
cross JOIN response_codes code
left join
(SELECT i.eventId
,code.responseCode
,COUNT(i.attendeeResponse) responseCount
FROM invitations i
JOIN response_codes code
ON code.responseCode = i.attendeeResponse
group by i.eventid, code.responsecode) t
on t.responsecode =code.responsecode and t.eventid = i.eventid
order by i.eventid, code.responsecode desc
Another lazy way could be:
SELECT B.EVENTID,A.RESPONSECODE,
IFNULL((SELECT COUNT(*) FROM INVITATIONS C WHERE C.EVENTID = B.EVENTID AND C.ATTENDEERESPONSE = A.RESPONSECODE),0) AS 'responseCount'
FROM
RESPONSE_CODES A,
INVITATIONS B
GROUP BY A.RESPONSECODE,B.EVENTID
ORDER BY EVENTID ASC,RESPONSECODE DESC
SQL Fiddle

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