I want to build something with an aliases column like below, but I don't know how to make it a Laravel query. The following is my SQL.
SELECT
d.*,
d.damaged_building,
d.total_victim
FROM
(
SELECT
delete_flg,
damage_id,
create_time,
reg_user_name,
municipality_id,
report_time,
district,
village,
disaster_type,
cause_of_disaster,
(
bd_major_damage1 + bd_minor_damage1 + bd_major_damage2 + bd_minor_damage2 + bd_major_damage3 + bd_minor_damage3
)
as damaged_building,
(
hi_hd_deaths + hi_hd_serious_injuries + hi_hd_minor_injuries + hi_hd_missing_persons + hi_hd_sick_persons
)
as total_victim
FROM
d_damage
WHERE
delete_flg = 0
ORDER BY
create_time DESC
)
d
I want to translate this to Eloquent of Laravel Query Builder for use in my controller.
You may try with this
DB::table('d_damage')
->where('delete_flg',0)
->orderBy('create_time', 'desc')
->select('delete_flg', 'damage_id', 'create_time', 'reg_user_name', 'municipality_id', 'report_time', 'district', 'village', 'disaster_type', 'cause_of_disaster',DB::raw('(bd_major_damage1 + bd_minor_damage1 + bd_major_damage2 + bd_minor_damage2 + bd_major_damage3 + bd_minor_damage3) as damaged_building'),DB::raw('(hi_hd_deaths + hi_hd_serious_injuries + hi_hd_minor_injuries + hi_hd_missing_persons + hi_hd_sick_persons) as total_victim'))
->get();
this may be not exactly but almost
If I were you just stick to learning the SQL Queries since you bring it anywhere you can learn alot of frameworks / tools, rather than investing your time in Laravel's. Anyway, you still can use sql queries in laravel using the raw expressions : https://laravel.com/docs/5.8/queries#raw-expressions
Related
I am taking the Google Data Analytics course on Coursera and in the video the instructor executed the following query:
SELECT
Date,
Region,
Small_Bags,
Large_Bags,
XLarge_Bags,
Total_Bags,
Small_Bags + Large_Bags + XLarge_Bags AS Total_Bags_Calc
FROM
`class-5-355317.avocado_data.avocado_prices`
After executing this query they then opened a different editor window on BigQuery and executed the following query referring to an alias in the query above without defineing it:
SELECT
*
FROM
`class-5-355317.avocado_data.avocado_prices`
WHERE
Total_Bags != Total_Bags_Calc
When I executed this query it did not work for me and I received this error: 'Unrecognized name: Total_Bags_Calc; Did you mean Total_Bags?'
This makes sense. Within this query, the alias 'Total_Bags_Calc' hadn't been used within that query and didn't have anything to pull, so I tried a workaround:
SELECT
Date,
Region,
Small_Bags,
Large_Bags,
XLarge_Bags,
Total_Bags,
(SELECT Small_Bags + Large_Bags + XLarge_Bags FROM `class-5355317.avocado_data.avocado_prices`) AS Total_Bags_Calc
FROM `class-5-355317.avocado_data.avocado_prices`
WHERE
Total_Bags != Total_Bags_Calc
From what I understood this should work since the subquery now held the alias 'Total_Bags_Calc' but I still received the error Unrecognized name: Total_Bags_Calc; Did you mean Total_Bags?
How can I make this query work, and is there any way to have a query reference another query in the same manner that theirs did in the example?
You'll want to select FROM the result of your first query, so try moving that subquery into the FROM clause.
For example,
SELECT
*
FROM
{{ your other query goes here }}
WHERE
Total_Bags != Total_Bags_Calc
Which would be:
SELECT
*
FROM
(SELECT
Date,
Region,
Small_Bags,
Large_Bags,
XLarge_Bags,
Total_Bags,
Small_Bags + Large_Bags + XLarge_Bags AS Total_Bags_Calc
FROM
`class-5-355317.avocado_data.avocado_prices`
) as subquery
WHERE
Total_Bags != Total_Bags_Calc
This is a really helpful technique to learn, so definitely learn it. However since you're doing something rather simple, you can actually get away with just coding that logic in your WHERE clause.
SELECT
Date,
Region,
Small_Bags,
Large_Bags,
XLarge_Bags,
Total_Bags,
Small_Bags + Large_Bags + XLarge_Bags AS Total_Bags_Calc
FROM
`class-5-355317.avocado_data.avocado_prices`
WHERE (Small_Bags + Large_Bags + XLarge_Bags) <> Total_Bags
Good Morning Tituslcuster!
I think I have spotted the issue.
Your query is creating an column named Total_Bags_Calc
When your code reaches the Where statement stuff, Total_Bags_Calc is the part that is breaking your code.
This is because it doesn't exist in the From table, but it does exist as a temporary name.
You can do two different things to fix this..
You can subquery this whole query, and do the Where Total_Bags_Calc on the outside query.
Or you can replace the Total_Bags_Calc with the actual formula that you used to calculate Total_Bags_Calc.
Here try this one:
select x2.* from (
SELECT
Date,
Region,
Small_Bags,
Large_Bags,
XLarge_Bags,
Total_Bags,
( Small_Bags + Large_Bags + XLarge_Bags ) AS Total_Bags_Calc
FROM 'class-5-355317.avocado_data.avocado_prices'
) as x2
where x2.Total_Bags != x2.Total_Bags_Calc
I'm trying to write an Oracle query to join data from 4 different tables. The code is below:
SELECT
PROJ.PRJ_NO, PROJ.PRJ_NAME, PROJ.PRJ_BEG_DATE, PROJ.PRJ_END_DATE, PORT.TIER1_NAME, PORT.TIER2_NAME, PORT.TIER3_NAME, MAX(A.FIS_WK_END_DATE) AS "FISCAL_WEEK", SUM(A.ABDOL) AS "AAB_DOL", SUM(A.VHDOL) AS "AVH_DOL", SUM(A.ADOL) AS "AA_DOL", SUM(A.DCDOL) AS "ADC_DOL", SUM(A.DCGADOL) AS "ADC_GA_DOL", SUM(A.COM) AS "AM_DOL", SUM(A.FE) AS "AFE_DOL", SUM(A.IE) AS "AIE_DOL", SUM(A.OTHER) AS "AR_DOL", SUM(A.MTSFT) AS "AS_FT", SUM(A.MTSST) AS "AS_ST", SUM(A.ACTST) AS "AL_ST", SUM(A.ACTFT) AS "ALL_FT", MAX(P.SNAPSHOT_DATE) as "SNAP_DATE", P.FINSCN_TYPE, SUM(P.ABDOL) AS "PAB_DOL", SUM(P.VHDOL) AS "PVH_DOL", SUM(P.DCDOL) AS "PDC_DOL", SUM(P.TCI_DOL) AS "PCI_GA_DOL", SUM(P.GADOL) AS "PN_GA_DOL", SUM(P.COM) AS "PN_COM", SUM(P.FEE) AS "PN_FEE", SUM(P.D_IE) AS "PN_MOIE", SUM(P.OTHER) AS "PN_OTHER"
FROM PROJ_TASK_VW PROJ
LEFT JOIN PORTFOLIO_VW PORT
ON PROJ.TASKNO = PORT.TASKNO
LEFT JOIN ACTUAL_VW A
ON PROJ.TASKNO = A.CURR_TASKNO
LEFT JOIN BUDG_DOLL_VW P
ON PROJ.TASKNO = P.CURR_TASKNO
WHERE TO_CHAR(PROJ.PRJ_END_DATE, 'YYYY-MM-DD') > '2018-10-01'
AND PROJ.P_FLAG = 'N'
AND (PROJ.P_TYPE LIKE 'D-%' OR PROJ.P_TYPE LIKE '%MR%' OR PROJ.P_TYPE LIKE '%ID%')
AND (SUBSTR(PROJ.PRJ_NO,3,3) != 'BP' AND SUBSTR(PROJ.PRJ_NO,3,3) != 'PJ')
AND (P.FINSCN_TYPE = 'SR' OR P.FINSCN_TYPE = 'BUG')
AND (A.ABDOL + A.VHDOL + A.ADOL + A.DCDOL + A.DCGADOL + A.COM +
A.FE + A.IE + A.OTHER) <> 0
GROUP BY
PROJ.PRJ_NO,
PROJ.PRJ_NAME,
PROJ.PRJ_BEG_DATE,
PROJ.PRJ_END_DATE,
PORT.TIER1_NAME,
PORT.TIER2_NAME,
PORT.TIER3_NAME,
P.FINSCN_TYPE
My overall intent is to bring all of the select fields into a single table using left joins (using table "PROJ" as the parent table and the remaining tables providing child data based on the data returned from the "PROJ" table. When the query is ran it times out after about 30mins. Is there a better way to write this query to where I can build the table I need without timing out???
First, there's no way to answer this question without an execution plan. What columns do you have indexed? But here are some things I noticed.
WHERE TO_CHAR(PROJ.PRJ_END_DATE, 'YYYY-MM-DD') > '2018-10-01'
Your column is a date, so you should be comparing to a date, rather than converting to a VARCHAR2 and doing an inequality on strings.
AND (PROJ.P_TYPE LIKE 'D-%' OR PROJ.P_TYPE LIKE '%MR%' OR PROJ.P_TYPE LIKE '%ID%')
I'm not sure, but these will likely not be very performant because of the wildcards. Indexes might make these better, but I never remember how wildcard searches work with indexes.
AND (SUBSTR(PROJ.PRJ_NO,3,3) != 'BP' AND SUBSTR(PROJ.PRJ_NO,3,3) != 'PJ')
These do nothing since your two SUBSTRs return strings of 3 characters long and you are comparing them to 2 character long strings.
AND (A.ABDOL + A.VHDOL + A.ADOL + A.DCDOL + A.DCGADOL + A.COM + A.FE + A.IE + A.OTHER) <> 0
Do you actually care about the sum here, or are you just checking that one or more of these values is non-zero. If these values are always > 0, then you're better off replacing this with:
AND ( a.ABDOL > 0 OR A.VHDOL > 0 ...
I was curious if there is an easy way to sum all attributes in a model without it looking repetitive, and not DRY.
I have a donation app, and this is how I summed everything:
def self.total_donations
array = Category.pluck(
'SUM(toilet_paper)',
'SUM(dental_hygiene)',
'SUM(first_aid)',
'SUM(general_hygiene)',
'SUM(underwear_socks)',
'SUM(blankets)',
'SUM(school_supplies)',
'SUM(diapers)').flatten.compact
array.inject(0){|sum, x| sum + x}
end
It's just ugly, but I don't know how to get around adding all of them up without doing something like this.
Thanks!
Check out this one:
def self.total_donations
sum("toilet_paper + dental_hygiene + first_aid + general_hygiene + underwear_socks + blankets + school_supplies + diapers")
end
The generated SQL:
SELECT SUM(toilet_paper + dental_hygiene + first_aid + general_hygiene + underwear_socks + blankets + school_supplies + diapers)
FROM "categories"
short (no shorter possible)
efficient (all the processing is done on the database layer)
Note, that in the class instance methods you don't have to use Category, because it is self (assuming, the method is in the Category model).
I need to create a file path from 3 columns in a SQL query. This will be utilized in a file once everything is completed. I have tried using CONCAT and string methods for the columns but no luck. The query is provided below.
SELECT
dbo.TBIndexData.DocGroup,
dbo.TBIndexData.Index1 AS Title,
dbo.TBIndexData.Index2 AS Meeting_Date,
dbo.TBIndexData.Index3 AS Meeting_Number,
dbo.TBIndexData.Index4 AS Meeting_Type,
dbo.TBIndexData.Index5 AS Doc_Name,
dbo.TBIndexData.Index6 AS Doc_Type,
dbo.TBIndexData.Index7 AS Meeting_Page,
dbo.TBIndexData.Index8 AS Notes,
dbo.TBIndexData.Index9 AS TBUser,
dbo.TBIndexData.Index10 AS Date_Scanned,
CONCAT (dbo.TBPrimary.FileDir + '\' + dbo.TBPrimary.TimsFileID + '.' + dbo.TBPrimary.FileExtension) AS FilePath
FROM
dbo.TBIndexData
JOIN
dbo.TBPrimary ON dbo.TBIndexData.DocGroup = dbo.TBPrimary.DocGroup
In SQL Server 2008 you need something like
SELECT I.DocGroup,
I.Index1 AS Title,
I.Index2 AS Meeting_Date,
I.Index3 AS Meeting_Number,
I.Index4 AS Meeting_Type,
I.Index5 AS Doc_Name,
I.Index6 AS Doc_Type,
I.Index7 AS Meeting_Page,
I.Index8 AS Notes,
I.Index9 AS TBUser,
I.Index10 AS Date_Scanned,
P.FileDir + '\' + CAST(P.TimsFileID AS VARCHAR(10)) +
'.' + P.FileExtension AS FilePath
FROM dbo.TBIndexData I
JOIN dbo.TBPrimary P
ON I.DocGroup = P.DocGroup
You shouldn't use schemaname.tablename in the SELECT list. This is not officially supported grammar. Just use tablename or give an alias.
(Using two part names there can lead to confusing errors if calling properties of columns of CLR datatypes)
Try to use CONCAT with commas
CONCAT (dbo.TBPrimary.FileDir, '\', dbo.TBPrimary.TimsFileID, '.', bo.TBPrimary.FileExtension) AS FilePath
I am trying to work out how to convert the order by code bellow that I am currently using in db_query to db_select.
The query sorts users by how well the match the current logged in user. I am also using some WHERE statements to remove users that are totally incompatible before running the rest through the order by calculation to speed up the query, so I don't want to run it as a select expression.
ORDER BY (10*(s.field_smoker_value * :field_smoker_pref_value) +
10*(sp.field_smoker_pref_value * :field_smoker_value) +
15*(p.field_pet_value * :field_pet_pref_value) +
15*(pp.field_pet_pref_value * :field_pet_value) +
5*(c.field_couple_value * :field_couple_pref_value) +
5*(cp.field_couple_pref_value * :field_couple_value))ASC