`select dea.continent, dea.location, dea.date, dea.population, vac.new_vaccinations
SUM(CONVERT(int,vac.new_vaccinations)) OVER (Partition by dea.Location Order by dea.location, dea.Date) as RollingPeopleVaccinated from
Portfolio.CovidDeaths as dea
join portfolio.covidvaccine as vac
on dea.location = vac.location and dea.date = vac.date
where dea.continent is not null
order by 2,3`
'SUM(CONVERT(signed int,vac.new_vaccinations)) error'
'I Tried The unsigned integer and signed int.'
Try using CAST:
SUM(CAST(vac.new_vaccinations AS UNSIGNED))
Related
I'm trying to sort my query results by date, then within each timeframe by if the status is 'sold', then if the status is 'contingent', then if the status is 'canceled'. Nothing I do to the ORDER BY clause seems to work. I would really appreciate some insight into what I'm doing wrong. Here's my query as it is now:
SELECT
subdivision community
, lot_number lot
, homeowner buyer
, agent_initials agent
, date_sold date
, sales.plan plan
, sales.inv_pre type
, sold_price price
, 'sold' status
, SUBSTRING_INDEX(SUBSTRING_INDEX(date_sold,'-',2),'-',-1) month
FROM
sales
JOIN
third_party_sources
ON sales.job_id = third_party_sources.job_id
WHERE
sales.is_contingent is null
AND sales.date_sold BETWEEN :startDate AND :endDate
OR sales.is_contingent = 0
AND sales.date_sold BETWEEN :startDate AND :endDate
UNION
SELECT
subdivision community
, lot_number lot
, homeowner buyer
, agent_initials agent
, date_sold date
, sales.plan plan
, sales.inv_pre type
, sold_price price
, 'contingent' status
, SUBSTRING_INDEX(SUBSTRING_INDEX(date_sold,'-',2),'-',-1) month
FROM
sales
JOIN
third_party_sources
ON sales.job_id = third_party_sources.job_id
WHERE
sales.is_contingent
AND sales.date_sold BETWEEN :startDate AND :endDate
UNION
SELECT
subdivision community
, lot_number lot
, buyer_name buyer
, agent_initials agent
, date_canceled date
, null plan
, null type
, null price
, 'canceled' status
, SUBSTRING_INDEX(SUBSTRING_INDEX(date_canceled,'-',2),'-',-1) month
FROM
cancellations
JOIN
third_party_sources
ON cancellations.job_id = third_party_sources.job_id
WHERE
cancellations.date_cancelled BETWEEN :startDate AND :endDate
ORDER BY
date
, status = 'sold'
, status = 'contingent'
, status = 'canceled'
I think you want:
ORDER BY date, FIELD(status, 'sold', 'contingent', 'canceled')
This assumes that these are the only three values. If there are more values, then your method would work . . . with DESC:
ORDER BY date, (status = 'sold') DESC, (status = 'contingent') DESC, (status = 'canceled') DESC
In my Laravel 5.7/mysql 5 app I have a table with votes results:
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`vote_item_id` INT(10) UNSIGNED NOT NULL,
`user_id` INT(10) UNSIGNED NOT NULL,
`is_correct` TINYINT(1) NOT NULL DEFAULT '0',
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
where boolean is_correct field is if answer was correct or incorrect.
I need to get data on percents of correct answers.
Creating such request
$voteItemUsersResultsCorrect = VoteItemUsersResult:: // Grouped by vote name
getByIsCorrect(true)->
getByCreatedAt($filter_voted_at_from, ' > ')->
getByCreatedAt($filter_voted_at_till, ' <= ')->
getByUserId($filterSelectedUsers)->
getByVote($filterSelectedVotes)->
getByVoteCategories($filterSelectedVoteCategories)->
getByVoteIsQuiz(true)->
getByVoteStatus('A')->
select( \DB::raw('count(vote_item_users_result.id) as count, votes.id, votes.name as vote_name') )->
orderBy('vote_name', 'asc')->
groupBy( 'votes.id' )->
groupBy( 'vote_name' )->
join(\DB::raw('vote_items'), \DB::raw('vote_items.id'), '=', \DB::raw('vote_item_users_result.vote_item_id'))->
join(\DB::raw('votes '), \DB::raw('votes.id'), '=', \DB::raw('vote_items.vote_id'))->
get();
I can get number of correct votes with sql request.
SELECT count(vote_item_users_result.id) AS count, votes.id, votes.name AS vote_name
FROM `vote_item_users_result`
INNER JOIN vote_items on vote_items.id = vote_item_users_result.vote_item_id
INNER JOIN votes on votes.id = vote_items.vote_id
WHERE `vote_item_users_result`.`is_correct` = '1' AND vote_item_users_result.created_at > '2018-08-01' AND vote_item_users_result.created_at <= '2018-09-22 23:59:59' AND `votes`.`is_quiz` = '1' AND `votes`.`status` = 'A'
GROUP BY `votes`.`id`, `vote_name`
ORDER BY `vote_name` asc
I know a way to get 2nd similar request with is_correct = '0' and on php side to combine results with percent calculating,
but I wonder if that could be done with eloquent in 1 request?
If yes, how ?
Thanks!
One correct raw MySQL would use conditional aggregation:
SELECT
v.id,
100.0 * COUNT(CASE WHEN vir.is_correct = 1 THEN 1 END) / COUNT(*) AS pct_correct,
100.0 * COUNT(CASE WHEN vir.is_correct = 0 THEN 1 END) / COUNT(*) AS pct_incorrect
FROM votes v
INNER JOIN vote_items vi
ON v.id = vi.vote_id
INNER JOIN vote_item_users_result vir
ON vi.id = vir.vote_item_id
WHERE
vir.created_at > '2018-08-01' AND vir.created_at < '2018-09-23' AND
v.is_quiz = '1' AND
v.status = 'A'
GROUP BY
v.id;
Now we can try writing Laravel code for this:
DB::table('vote')
->select('vote.id',
DB::raw('100.0 * COUNT(CASE WHEN vir.is_correct = 1 THEN 1 END) / COUNT(*) AS pct_correct'),
DB::raw('100.0 * COUNT(CASE WHEN vir.is_correct = 0 THEN 1 END) / COUNT(*) AS pct_incorrect'))
->join('vote_items', 'votes.id', '=', 'vote_items.vote_id')
->join('vote_item_users_result', 'vote_items.id', '=', 'vote_item_users_result.vote_item_id ')
->where([
['vote_item_users_result.created_at', '>', '2018-08-01'],
['vote_item_users_result.created_at', '<', '2018-09-23'],
['vote.is_quiz', '=', '1'],
['vote.status', '=', 'A']
])
->groupBy('vote.id')
->get();
I want to get the sum of li_units_bought for rows based on li_order_id.
I am joining multiple tables for it. Here is my query:
$query = (new \yii\db\Query())
->select('oid, ord_tracking_no as `Tracking No`, site_name as Region,adv_name as Advertiser, line_id as LineId, li_name as LineName
, li_status as StatusCode, prd_desc as Product, li_version as Version, date_format(lrh_updated_date,"%Y-%m-%d %H:%i") as `Submit Date`
, date_format(li_start_date,"%Y-%m-%d %H:%i") as `Start Date`
, date_format(li_end_date,"%Y-%m-%d %H:%i") as `End Date`, li_is_rush as isRushOrder
, li_type as Type, ord_assigned_user as `Assigned User`, status_desc as Status
, SUM(`li_units_bought`) as Goal
, ldp_total_delivery as `Delivered`
, if(li_type="STANDARD",((ldp_pacing*180)/100)+1,((ldp_pacing+1)*1*180)) as Pacing
, li_cost_type as `Cost Type`
, ord_total_budget as `Total Budget`
, li_is_automated
,li_target_server as Adserver
,li_del_pac_indicator as `DFP Report`
,li_submit_by
' )
->from('lineitems')
->innerJoin('orders','oid = li_order_id')
->leftJoin('advertisers','adv_id=ord_adv_id')
->leftJoin('sites','site_id=ord_site_id')
->leftJoin('products','prd_id=li_product')
->leftJoin('status_ref','status_id=li_status')
->leftJoin('users',"user_id='".$userid."'")
->leftJoin('user_role_profiles','urp_id=user_primary_role')
->leftJoin('lineitem_delivery_pacing','ldp_line_id = line_id')
->innerJoin("user_site_assoc","usc_site_id=ord_site_id and usc_userid='".$_SESSION['userId']."'")
->innerJoin("lineitem_revision_history", "lrh_lineitemid = line_id")
->where(" li_status not in ('Z','X') $cond")
->andWhere("li_order_id = oid")
->groupBy('line_id');
I am getting only the li_units_bought for one row. Not the sum of the rows having the same li_order_id.
Can someone tell me what I'm doing wrong?
I have a query and it uses MySQL as its database. Now I'm going nuts as to why it took 11 minutes to render result, I have like 7K+ records on my table and running a recursive subquery(?), I'm not entirely sure if this is what eats up the memory but if you could look and give some remedy as to how can this be optimized I would be very happy and contented...
My goal is to compress records relative to a particular person... And rank them based on time finished.
Table structure:
CREATE TABLE `temptbl_raceeventresult_step1` (
`RunCatEventId` INT(11) NOT NULL,
`RunEventId` INT(11) NOT NULL,
`CategoryId` INT(11) NOT NULL,
`FullName` VARCHAR(255) NOT NULL,
`BIB` INT(11) NOT NULL,
`Category` DECIMAL(16,3) NOT NULL,
`Ord` INT(11) NOT NULL,
`TransitionId` INT(11) NOT NULL,
`Time` DATETIME NOT NULL)
COLLATE='latin1_swedish_ci'ENGINE=MyISAM;
//Query
SELECT
UCASE(g1.Name) Name
,g1.BIB
,g1.TimeDerived
,g1.CategoryName
,g1.TotalPace
,g1.Category
,COUNT(*) AS rank
FROM
(
SELECT
a.FullName Name,
a.RunCatEventId,
a.RunEventId,
a.CategoryId,
a.BIB,
a.Category,
a.Ord,
a.TransitionId,
SEC_TO_TIME(SUM(TIME_TO_SEC(Time) - (SELECT TIME_TO_SEC(Time) TimeMinuend FROM temptbl_raceeventresult_step1 WHERE BIB = a.bib AND (Ord + 1) = a.Ord AND CategoryId = a.CategoryId))) TimeDerived,
SEC_TO_TIME(SUM(TIME_TO_SEC(Time) - (SELECT TIME_TO_SEC(Time) TimeMinuend FROM temptbl_raceeventresult_step1 WHERE BIB = a.bib AND (Ord + 1) = a.Ord AND CategoryId = a.CategoryId)) / a.Category) TotalPace
FROM temptbl_raceeventresult_step1 a
JOIN (SELECT #cat:=null) xyz
GROUP BY a.RunCatEventId, a.RunEventId, a.CategoryId, a.FullName, a.BIB
) g1
JOIN
(
SELECT
a.FullName Name,
a.RunCatEventId,
a.RunEventId,
a.CategoryId,
a.BIB,
a.Category,
a.Ord,
a.TransitionId,
SEC_TO_TIME(SUM(TIME_TO_SEC(Time) - (SELECT TIME_TO_SEC(Time) TimeMinuend FROM temptbl_raceeventresult_step1 WHERE BIB = a.bib AND (Ord + 1) = a.Ord AND CategoryId = a.CategoryId))) TimeDerived,
SEC_TO_TIME(SUM(TIME_TO_SEC(Time) - (SELECT TIME_TO_SEC(Time) TimeMinuend FROM temptbl_raceeventresult_step1 WHERE BIB = a.bib AND (Ord + 1) = a.Ord AND CategoryId = a.CategoryId)) / a.Category) TotalPace
FROM temptbl_raceeventresult_step1 a
JOIN (SELECT #cat:=null) xyz
GROUP BY a.RunCatEventId, a.RunEventId, a.CategoryId, a.FullName, a.BIB
) g2
ON (g2.TimeDerived, g2.bib) <= (g1.TimeDerived, g1.bib) AND g1.Category = g2.Category
WHERE g2.Category = 5 AND g1.RunEventId = 3
GROUP BY g1.Name
,g1.BIB
,g1.TimeDerived
,g1.CategoryName
,g1.TotalPace
,g1.Category
ORDER BY g1.Category, rank
I am very close to completing this difficult query. It's quite long, so hopefully not too overwhelming. But in my case statment in the select block I am referencing a union from my where statement. It is giving me "MySQL Database Error: Unknown column 'U.EmpID' in 'where clause'". Any help would be much appreciated. And here is the query:
SELECT U.EmpID,
CASE
WHEN ((SELECT COUNT(*)
FROM (SELECT *
FROM timeclock_copy tp
WHERE PunchEvent = 'breakin'
AND DATE(tp.PunchDateTime) =
'2013-11-12'
AND tp.EmpID = U.EmpID) AS s) > 1)
AND ((SELECT COUNT(*)
FROM (SELECT *
FROM timeclock_copy tp
WHERE PunchEvent = 'breakout'
AND DATE(tp.PunchDateTime) =
'2013-11-12'
AND tp.EmpID = U.EmpID) AS s) > 1)
THEN
"MULTIPLE BREAKS"
ELSE
"ONE BREAK"
END
AS Lunch
FROM ((SELECT `enter`.EmpID,
`enter`.PunchDateTime AS `time`,
DATE_FORMAT(`enter`.PunchDateTime, '%m-%d-%Y')
AS 'Punch Date',
TIMESTAMPDIFF(SECOND,
`enter`.PunchDateTime,
'2003-05-01 00:00:00')
AS `delta`
FROM timeclock_copy AS `enter`
WHERE `enter`.`In-Out` = 1)
UNION
(SELECT `leave`.EmpID,
`leave`.PunchDateTime AS `time`,
DATE_FORMAT(`leave`.PunchDateTime, '%m-%d-%Y')
AS 'Punch Date',
-TIMESTAMPDIFF(SECOND,
`leave`.PunchDateTime,
'2003-05-01 00:00:00')
AS `delta`
FROM timeclock_copy AS `leave`
WHERE `leave`.`In-Out` = 0)) AS U
LEFT JOIN testclb.prempl pe ON u.EmpID = pe.prempl
WHERE DATE(U.`time`) >= '2013-11-12' AND DATE(U.`time`) < '2013-11-13'
GROUP BY date(U.`time`), EmpID
ORDER BY U.EmpID, U.`time` ASC
Subqueries in FROM clauses cannot be correlated with the outer statement. I think this is why you are getting the Unknown column 'U.EmpID' in 'where clause'" error.