I have table with query :
SELECT DATENAME(Month,TOPUP.tu_timestamp) AS MonthName, TM.terminal_name,
CAST(ROUND(ISNULL(TOPUP.tu_credit - NC.initial_bal, TOPUP.tu_credit) /
TOPUP.currency_rate, 2) AS decimal(18, 2)) AS
Top_Up_Value
FROM dbfastshosted.dbo.fh_mf_top_up_logs AS TOPUP
INNER JOIN dbo.cdf_terminal_user AS TU ON TOPUP.terminal_user_id =
TU.terminal_user_id
INNER JOIN dbo.cdf_currency AS CR ON TOPUP.currency_id = CR.currency_id
INNER JOIN dbo.cdf_cuid AS CU ON TOPUP.cu_id = CU.cu_id
INNER JOIN dbo.cdf_card_role AS CO ON CO.id = CU.card_role_id
INNER JOIN dbo.cdf_terminal_user_account AS UA ON UA.terminal_user_id =
TU.terminal_user_id
INNER JOIN dbo.cdf_terminal AS TM ON TM.terminal_id = UA.terminal_id
INNER JOIN dbfastshosted.dbo.fh_sales_map AS MA ON MA.tu_log_id =
TOPUP.tu_log_id
LEFT OUTER JOIN dbfastshosted.dbo.fh_mf_new_card_logs AS NC ON
MA.nc_log_id = NC.nc_log_id
WHERE (ISNULL(TOPUP.tu_credit - NC.initial_bal, TOPUP.tu_credit) > 0)
and YEAR(TOPUP.tu_timestamp) = '2017'
AND month(TOPUP.tu_timestamp) = 1
AND TM.terminal_id = 7
GROUP BY TOPUP.tu_log_id,DATENAME(Month,TOPUP.tu_timestamp),
TM.terminal_name,
TOPUP.tu_credit, NC.initial_bal, TOPUP.currency_rate, CU.card_type_id;
MonthName Terminal name Top Up Value
------------------------------------------------------
January Terminal 1 100
January Terminal 1 200
January Terminal 3 150
Feb Terminal 1 250
Feb Terminal 1 160
March Terminal 2 120
March Terminal 3 100
and i would like to have total sums of top up value according to months which look like this:
MonthName Top Up Value
-----------------------------------
January 450
February 410
March 220
-----
Dec
as i am beginner in sql , i dont have idea how to do it. Really need help on these. Thanks!
SELECT DATENAME(Month,TOPUP.tu_timestamp) AS MonthName,
SUM(CAST(ROUND(ISNULL(TOPUP.tu_credit - NC.initial_bal, TOPUP.tu_credit) /
TOPUP.currency_rate, 2) AS decimal(18, 2))) AS
Top_Up_Value
FROM dbfastshosted.dbo.fh_mf_top_up_logs AS TOPUP
INNER JOIN dbo.cdf_terminal_user AS TU ON TOPUP.terminal_user_id =
TU.terminal_user_id
look at your group by statement, the result you posted is displaying lesser number of columns then what you have in your query. Tweak it around and you will get your results
Try this
SELECT DATENAME(Month,TOPUP.tu_timestamp) AS MonthName,
SUM(CAST(ROUND(ISNULL(TOPUP.tu_credit - NC.initial_bal, TOPUP.tu_credit) /
TOPUP.currency_rate, 2) AS decimal(18, 2))) AS
Top_Up_Value
FROM dbfastshosted.dbo.fh_mf_top_up_logs AS TOPUP
INNER JOIN dbo.cdf_terminal_user AS TU ON TOPUP.terminal_user_id =
TU.terminal_user_id
INNER JOIN dbo.cdf_currency AS CR ON TOPUP.currency_id = CR.currency_id
INNER JOIN dbo.cdf_cuid AS CU ON TOPUP.cu_id = CU.cu_id
INNER JOIN dbo.cdf_card_role AS CO ON CO.id = CU.card_role_id
INNER JOIN dbo.cdf_terminal_user_account AS UA ON UA.terminal_user_id =
TU.terminal_user_id
INNER JOIN dbo.cdf_terminal AS TM ON TM.terminal_id = UA.terminal_id
INNER JOIN dbfastshosted.dbo.fh_sales_map AS MA ON MA.tu_log_id =
TOPUP.tu_log_id
LEFT OUTER JOIN dbfastshosted.dbo.fh_mf_new_card_logs AS NC ON
MA.nc_log_id = NC.nc_log_id
WHERE (ISNULL(TOPUP.tu_credit - NC.initial_bal, TOPUP.tu_credit) > 0)
and YEAR(TOPUP.tu_timestamp) = '2017'
AND month(TOPUP.tu_timestamp) = 1
AND TM.terminal_id = 7
GROUP BY DATENAME(Month,TOPUP.tu_timestamp)
Related
I have database like this http://sqlfiddle.com/#!9/e52c43
First query is :
SELECT m.tanggal, sum(mi.qty) as totalMuatan, mi.idPlastik
FROM tblMuatan m
LEFT JOIN tblMuatanIsi mi ON m.idMuatan = mi.idMuatan
WHERE m.tanggal='2020-03-15'
GROUP BY mi.idPlastik
The result is:
tanggal totalMuatan idPlastik
2020-03-15 85 1
2020-03-15 10 2
And second query is :
SELECT s.tanggal, sum(si.qty) as totalStok, si.idPlastik
FROM tblStok s
LEFT JOIN tblStokIsi si ON s.idStok = si.idStok
WHERE s.tanggal = '2020-03-15'
GROUP BY si.idPlastik
The result is :
tanggal totalStok idPlastik
2020-03-15 100 1
2020-03-15 200 2
I want to merge that 2 queries into single query with subquery
tanggal totalStok totalMuatan netTotal idPlastik
2020-03-15 100 85 15 1
2020-03-15 200 10 190 2
How to do the subquery in example above? Thank you for the support
Better to use COALESCE since you're using LEFT JOIN for the tables you are calculating SUM from to avoid no result for the records that have NULL values.
select m.tanggal, t.totalStok, sum(mi.qty) as totalMuatan, coalesce(t.totalStok,0)-coalesce(sum(mi.qty),0) as netTotal, mi.idPlastik
from tblMuatan m
LEFT JOIN tblMuatanIsi mi ON m.idMuatan = mi.idMuatan
JOIN (SELECT s.tanggal, sum(si.qty) as totalStok, si.idPlastik
FROM tblStok s
LEFT JOIN tblStokIsi si ON s.idStok = si.idStok
WHERE s.tanggal='2020-03-15'
GROUP BY s.tanggal,si.idPlastik) t on m.tanggal=t.tanggal and mi.idPlastik = t.idPlastik
group by m.tanggal, t.totalStok,mi.idPlastik
Please try..
SELECT T1.tanggal, T2.totalStok, T1.totalMuatan, (T2.totalStok - T1.totalMuatan), T1.idPlastik
FROM
(SELECT m.tanggal, sum(mi.qty) as totalMuatan, mi.idPlastik
FROM tblMuatan m
LEFT JOIN tblMuatanIsi mi ON m.idMuatan = mi.idMuatan
WHERE m.tanggal='2020-03-15'
GROUP BY mi.idPlastik)
as T1,
(SELECT s.tanggal, sum(si.qty) as totalStok, si.idPlastik
FROM tblStok s
LEFT JOIN tblStokIsi si ON s.idStok = si.idStok
WHERE s.tanggal = '2020-03-15'
GROUP BY si.idPlastik)
as T2
WHERE
T1.tanggal = T2.tanggal;
SELECT a.tanggal,
b.totalstok,
a.totalmuatan,
( totalstok - totalmuatan ) netTotal,
a.idplastik
FROM (SELECT convert(varchar, m.tanggal, 23) tanggal,
Sum(mi.qty) AS totalMuatan,
mi.idplastik
FROM #tblmuatan m
LEFT JOIN #tblmuatanisi mi
ON m.idmuatan = mi.idmuatan
WHERE m.tanggal = 1
GROUP BY mi.idplastik,
convert(varchar, m.tanggal, 23)) a
JOIN (SELECT convert(varchar, s.tanggal, 23) tanggal,
Sum(si.qty) AS totalStok,
si.idplastik
FROM #tblstok s
LEFT JOIN #tblstokisi si
ON s.idstok = si.idstok
WHERE s.tanggal = 1
GROUP BY si.idplastik,
convert(varchar, s.tanggal, 23)) b
ON a.idplastik = b.idplastik
Thank you for your comments I'll try this from a different angle.
How can this query be written to produce these results?
CompID CompeteID Casting Fishing Total
1 1 265.89 425.56 691.45
1 9 212.31 84.76 285.92
1 7 0.00 285.92 285.92
1 8 0.00 44.52 44.52
ORDER BY Total DESC
SELECT cs.CompID, ic.CompeteID
, MAX(IF(cast.CastType_ID BETWEEN 6 AND 12, cast.Length, 0)) + SUM(IF(cast.CastType_ID < 6, 40 - (cast.Length * 2), 0)) AS 'Casting'
FROM `comp-setup` cs
INNER JOIN `input-competitor` ic
ON cs.CompID = ic.Comp_ID
LEFT JOIN `input-casting` cast
ON cast.Compete_ID = ic.CompeteID
GROUP BY ic.CompeteID
UNION ALL
SELECT cs.CompID, ic.CompeteID
, SUM((iw.Weight * ca.Factor) + '1') AS 'Fishing'
FROM `comp-setup` cs
INNER JOIN `input-competitor` ic
ON cs.CompID = ic.Comp_ID
LEFT JOIN `input-weighin` iw
ON iw.Compete_ID = ic.CompeteID
INNER JOIN `input-catchpoints` ca
ON ca.PointsCatchID = iw.PointsCatch_ID
GROUP BY ic.CompeteID
Results from the above query, I have added break-line and Fishing header to separate data.
CompID CompeteID Casting
1 1 265.89
1 7 0
1 8 0
1 9 212.31
----------------------------------
Fishing
1 1 425.56
1 7 285.92
1 8 44.52
1 9 84.76
Days this has taken me to work out. I found this example today which lead me to this solution, please post if there is a better way? But this does what I need!
SELECT Sub1.CompID, Sub1.CompeteID, Sub2.Casting, Sub1.Fishing, Sub2.Casting + Sub1.Fishing AS Total
FROM
(SELECT cs.CompID, ic.CompeteID, SUM((iw.Weight * ca.Factor) + '1') AS Fishing
FROM `comp-setup` cs
INNER JOIN `input-competitor` ic ON cs.CompID = ic.Comp_ID
INNER JOIN `input-weighin` iw ON iw.Compete_ID = ic.CompeteID
INNER JOIN `input-catchpoints` ca ON ca.PointsCatchID = iw.PointsCatch_ID
INNER JOIN `list-grade` gr ON ic.Grade_ID = gr.GradeID
INNER JOIN `list-division` ld ON ic.Div_ID = ld.DivID
GROUP BY ic.CompeteID) Sub1
INNER JOIN
(SELECT cs.CompID, ic.CompeteID, MAX(IF(cast.CastType_ID BETWEEN 6 AND 12, cast.Length, 0)) + SUM(IF(cast.CastType_ID < 6, 40 - (cast.Length * 2), 0)) AS Casting
FROM `comp-setup` cs
INNER JOIN `input-competitor` ic ON cs.CompID = ic.Comp_ID
LEFT JOIN `input-casting` cast ON cast.Compete_ID = ic.CompeteID
GROUP BY ic.CompeteID) Sub2
ON Sub1.CompeteID = Sub2.CompeteID
ORDER BY Total DESC
Here is the post with the example I needed:
MYSQL LEFT JOIN with GROUP BY
I am facing 1 issue with MySql query:
select sum(h.total_rooms) as total_rooms from reservation_details as rd LEFT JOIN hotels as h ON rd.hotel_id = h.id left join `chains` as `c` on `c`.`id` = `h`.`chain_id` where YEAR(rd.created_at) = 2016 and MONTH(rd.created_at) = 5 and rd.status >= 50 and h.chain_id = 2 GROUP BY rd.hotel_id
Above query returns :
total_rooms
48216
7700
13250
But
I need sum of the query.
Try to use sum() function like this and use ROLLUP with your query.
select sum(h.total_rooms) as total_rooms from reservation_details as rd
LEFT JOIN hotels as h ON rd.hotel_id = h.id
left join `chains` as `c` on `c`.`id` = `h`.`chain_id`
where YEAR(rd.created_at) = 2016 and MONTH(rd.created_at) = 5
and rd.status >= 50 and h.chain_id = 2 GROUP BY rd.hotel_id
WITH ROLLUP
I need help about generating query for multiple column.
part of my tbl_advert_specific_fields_values table look like:
id advert_id field_name field_value
1 654 t1_sqft 50
2 655 t1_yearbuilt 1999
3 1521 t2_doorcount 5
4 656 t1_yearbuilt 2001
5 656 t1_sqft 29
6 654 t1_yearbuilt 2004
SELECT p.*, p.id AS id, p.title AS title, usr.id as advert_user_id,
p.street_num, p.street,c.icon AS cat_icon,c.title AS cat_title,c.title AS cat_title,
p.description as description,
countries.title as country_name,
states.title as state_name,
date_FORMAT(p.created, '%Y-%m-%d') as fcreated
FROM tbl AS p
LEFT JOIN tbl_advertmid AS pm ON pm.advert_id = p.id
INNER JOIN tbl_usermid AS am ON am.advert_id = p.id
LEFT JOIN tbl_users AS usr ON usr.id = am.user_id
INNER JOIN tbl_categories AS c ON c.id = pm.cat_id
INNER JOIN tbl_advert_specific_fields_values AS asfv ON asfv.advert_id = p.id
LEFT JOIN tbl_countries AS countries ON countries.id = p.country
LEFT JOIN tbl_states AS states ON states.id = p.locstate
WHERE p.published = 1 AND p.approved = 1 AND c.published = 1
AND (asfv.field_name = 't1_yearbuilt'
AND CONVERT(asfv.field_value,SIGNED) <= 2004 )
AND (asfv.field_name = 't1_sqft'
AND CONVERT(asfv.field_value,SIGNED) <= 50)
AND p.price <= 10174945 AND (p.advert_type_id = 1)
AND (c.id = 43 OR c.parent = 43)
GROUP BY p.id
ORDER BY p.price DESC
ok, the problem is in this asfv query part that are generated dynamically. It belong to objects which represent adverts by its specific fields. asfv is actually advert_specific_fields_values table (table name say all about it).
Without part:
AND (asfv.field_name = 't1_yearbuilt'
AND CONVERT(asfv.field_value,SIGNED) <= 2004 )
AND (asfv.field_name = 't1_sqft'
AND CONVERT(asfv.field_value,SIGNED) <= 50)
query return all adverts that belong on advert_type_id and price of them are less than 10.174.945,00 €.
All what I need is query update that return only adverts, for example t1_yearbuilt less than 2005 and t1_sqft less than 51 (advert_id => 654,656).
I also need query for values between for example t1_sqft >=30 AND t1_sqft <=50 (advert_id => 654).
Can anybody know how, update this query?
TNX
I have to write a query where, I need to fetch records for last week, last month, and for all.
For this problem I wrote 3 diffrent queries (for last week, for last month and for all)
For Weekly Info :-
SELECT bu.brand_name AS 'Brand_Name',COUNT(s.unique) AS '# Item Sold',SUM(s.price) AS 'Total_Price'
FROM item_details s
LEFT JOIN sales_order o ON s.fk_sales_order = o.id_sales_order
LEFT JOIN customer_info AS c ON o.fk_customer_id = c.id_customer
LEFT JOIN simple_details cc ON s.unique = cc.unique
LEFT JOIN config_details cf ON cc.fk_config_id = cf.config_id
LEFT JOIN brand_details cb ON cf.fk_brand_id = cb.brand_id
LEFT JOIN category_details ctc ON cf.fk_category_id = ctc.category_id
LEFT JOIN gender_details g ON cf.fk_gender_id = g.gender_id
LEFT JOIN buyers AS bu ON bu.brand_name = cb.name AND bu.category_name = ctc.name AND bu.gender = g.name
WHERE bu.buyers = 'xyz' AND DATE_FORMAT(o.created_date,'%Y-%m-%d') >= #weekstartdate AND DATE_FORMAT(o.created_date,'%Y-%m-%d') <= #weekenddate
GROUP BY bu.brand_name
For Monthly Info :-
SELECT bu.brand_name AS 'Brand_Name',COUNT(s.unique) AS '# Item Sold',SUM(s.price) AS 'Total_Price'
FROM item_details s
LEFT JOIN sales_order o ON s.fk_sales_order = o.id_sales_order
LEFT JOIN customer_info AS c ON o.fk_customer_id = c.id_customer
LEFT JOIN simple_details cc ON s.unique = cc.unique
LEFT JOIN config_details cf ON cc.fk_config_id = cf.config_id
LEFT JOIN brand_details cb ON cf.fk_brand_id = cb.brand_id
LEFT JOIN category_details ctc ON cf.fk_category_id = ctc.category_id
LEFT JOIN gender_details g ON cf.fk_gender_id = g.gender_id
LEFT JOIN buyers AS bu ON bu.brand_name = cb.name AND bu.category_name = ctc.name AND bu.gender = g.name
WHERE bu.buyers = 'xyz' AND DATE_FORMAT(o.created_date,'%Y-%m-%d') >= #monthstartdate AND DATE_FORMAT(o.created_date,'%Y-%m-%d') <= #monthenddate
GROUP BY bu.brand_name
For All Records :-
SELECT bu.brand_name AS 'Brand_Name',COUNT(s.unique) AS '# Item Sold',SUM(s.price) AS 'Total_Price'
FROM item_details s
LEFT JOIN sales_order o ON s.fk_sales_order = o.id_sales_order
LEFT JOIN customer_info AS c ON o.fk_customer_id = c.id_customer
LEFT JOIN simple_details cc ON s.unique = cc.unique
LEFT JOIN config_details cf ON cc.fk_config_id = cf.config_id
LEFT JOIN brand_details cb ON cf.fk_brand_id = cb.brand_id
LEFT JOIN category_details ctc ON cf.fk_category_id = ctc.category_id
LEFT JOIN gender_details g ON cf.fk_gender_id = g.gender_id
LEFT JOIN buyers AS bu ON bu.brand_name = cb.name AND bu.category_name = ctc.name AND bu.gender = g.name
WHERE bu.buyers = 'xyz'
GROUP BY bu.brand_name
and these are working fine (giving currect output).
But problem is that, I have to merge these three queries in single one.
Where output should be as
Brand name, item_sold(week), total_price(week),item_sold(month), total_price(month),item_sold(all), total_price(all)
How can I write this query?
Without looking deep into your code, the obvious solution would be
SELECT
all.brand_name
pw.items_sold items_sold_week
pw.total_price total_price_week
pm.items_sold items_sold_month
pm.total_price total_price_month
all.items_sold items_sold_all
all.total_price total_price_all
FROM
(your all-time select) all
JOIN (your per-month select) pm ON all.brand_name = pm.brand_name
JOIN (your per-week select) pw ON all.brand_name = pw.brand_name
Though you probably should rethink your entire approach and make sure whether you really want that kind of logic in a DB layer or it is better to be in your application.
You could use case to limit aggregates to a subset of rows:
select bu.brand_name
, count(case when date_format(o.created_date,'%Y-%m-%d') >= #weekstartdate
and date_format(o.created_date,'%Y-%m-%d') <= #weekenddate
then 1 end) as '# Item Sold Week'
, sum(case when date_format(o.created_date,'%Y-%m-%d') >= #weekstartdate
and date_format(o.created_date,'%Y-%m-%d') <= #weekenddate
then s.price end) as 'Total_Price Week'
, count(case when date_format(o.created_date,'%Y-%m-%d') >= #monthstartdate
and date_format(o.created_date,'%Y-%m-%d') <= #monthstartdate
then 1 end) as '# Item Sold Month'
, ...
If all three selects uses the same fields in the results, you can UNION them:
SELECT *
FROM (SELECT 1) AS a
UNION (SELECT 2) AS b
UNION (SELECT 3) AS c
If you need to tell week/mon/all records from each other - just add constant field containing "week" or "mon"
You cam use the UNION.keyword between the queries to bundle them.together BUT tje column types and sequence must be the same in all queries. You could add an identifier to each set