How to display result and handle errors # 1242? - mysql

I want to:
if the value qty_out! = 0, then set qty_out = 0
Help me to display results
SELECT
SUBSTR(stok_control.tgl_faktur,9,2) AS 'tanggal',
SUBSTR(stok_control.tgl_faktur,6,2) AS 'bulan',
CONCAT(
(SELECT(
IFNULL(stok_control.faktur_beli,''))
)
,
(SELECT(
IFNULL(stok_control.faktur_jual,''))
)
) AS 'faktur',
bahan.id AS 'kode_bahan',
bahan.nm_bahan AS 'nama_bahan',
stok_control.qty_in AS 'masuk',
(
SELECT IF(stok_control.qty_out != '',0,0)
FROM
stok_control
WHERE
stok_control.faktur_beli !=''
) AS 'keluar'
FROM
stok_control
LEFT JOIN bahan ON stok_control.id_bahan=bahan.id
#eggyal, I have changed your code to be:
SELECT
SUBSTR(sc.tgl_faktur, 9, 2) AS 'tanggal',
SUBSTR(sc.tgl_faktur, 6, 2) AS 'bulan',
CONCAT(
IFNULL(sc.faktur_beli, ''),
IFNULL(sc.faktur_jual, '')
) AS 'faktur',
b.id AS 'kode_bahan',
b.nm_bahan AS 'nama_bahan',
(SELECT IFNULL(sc.qty_in,0)) AS 'masuk',
(SELECT
(
IF(faktur_beli <> '',
0,
(SELECT sc.qty_out)
)
)
) AS 'qty_out'
FROM
stok_control sc LEFT JOIN bahan b ON sc.id_bahan = b.id
I've tried to reference an existing but still error...

I want to:
if the value qty_out! = 0, then set qty_out = 0
Do you mean that you want qty_out to be 0 irrespective of its original value?
SELECT SUBSTR(sc.tgl_faktur, 9, 2) AS tanggal,
SUBSTR(sc.tgl_faktur, 6, 2) AS bulan,
CONCAT(
IFNULL(sc.faktur_beli, ''),
IFNULL(sc.faktur_jual, '')
) AS faktur,
b.id AS kode_bahan,
b.nm_bahan AS nama_bahan,
sc.qty_in AS masuk,
0 AS qty_out
FROM stok_control sc LEFT JOIN bahan b ON sc.id_bahan = b.id

Related

Left outer join MYSQL returning duplicate rows

I have this MYSQL Query:
select
sc.supplier,
sq.query_value,
sc.cnv_name as name,
sc.cnv_id,
sq.query_type_id,
qt.query_type_desc,
date_format(sq.query_date, '%d/%m/%Y') as query_date,
qs.query_status,
sq.sla_count,
sq.sla_state,
sq.assigned_to,
IfNull(teams.team_count, 0) team_count,
if(
sq.sla_state is null
OR sq.sla_state = '',
'',
if(
sq.sla_state = 0,
'Query Handler',
if(
sq.sla_state = 1,
'Team Leader',
if(
sq.sla_state = 2,
'Manager',
if(
sq.sla_state = 3,
'Senior Manager',
'Senior Manager (GSCOP BREACH)'
)
)
)
)
) as sla_state_desc,
if(
team_count <= 0
OR team_count is null,
'',
if(team_count > 1, '(multiple)', pt.team_desc)
) as team
from
supconversation sc
left outer join supconvers_querydtls sq on sq.cnv_id = sc.cnv_id
left outer join querytype qt on qt.query_type_id = sq.query_type_id
left outer join querystatus qs on qs.query_status_id = sq.query_status_id
left outer join (
select
count(*) team_count,
tu.user_id
from
teamusers tu,
supconvers_querydtls sq2
where
tu.user_id = sq2.assigned_to
) teams on (teams.user_id = sq.assigned_to)
left outer join teamusers tu on tu.user_id = sq.assigned_to
left outer join portalteam pt on pt.team_id = tu.team_id
where
sc.supplier = 'SUPTEST1'
and sc.cnv_type = 'Q'
order by
query_date desc
What I am trying to do is check if a user has a record in teamusers. The user can be a part of more than 1 team. This is stored in the teamusers table with the columns team_id, user_id. If a user has more than 1 record in teamusers then return team value as (multiple). Otherwise, return the team_desc found in the portalteam table. The portalteam table consists of the columns team_id,team_desc.
This query seems to work but it's returning duplicate rows. I imagine this is because there are multiple records for some users in teamusers. How would I go about fixing this issue?
If you really get duplicated rows then you could try using a select DISTINCT
select distinct
sc.supplier,
sq.query_value,
sc.cnv_name as name,
sc.cnv_id,
sq.query_type_id,
qt.query_type_desc,
date_format(sq.query_date, '%d/%m/%Y') as query_date,
qs.query_status,
sq.sla_count,
sq.sla_state,
sq.assigned_to,
IfNull(teams.team_count, 0) team_count,
if(
sq.sla_state is null
OR sq.sla_state = '',
'',
if(
sq.sla_state = 0,
'Query Handler',
if(
sq.sla_state = 1,
'Team Leader',
if(
sq.sla_state = 2,
'Manager',
if(
sq.sla_state = 3,
'Senior Manager',
'Senior Manager (GSCOP BREACH)'
)
)
)
)
) as sla_state_desc,
if(
team_count <= 0
OR team_count is null,
'',
if(team_count > 1, '(multiple)', pt.team_desc)
) as team
from
supconversation sc
.....
.....

How to hide a column in output result in Mysql?

select historic_betfair_win_prices.sf_name,historic_runners.finish_position,historic_runners.official_rating,historic_betfair_win_prices.date, historic_betfair_win_prices.bsp,
if(finish_position = 1 , #b:=#b+1,#b:=#b) opening_position,
if(finish_position = 1 , #last_op:=official_rating,#last_op:=#last_op)last_opening_position,
cast(if(#b = 0 or finish_position = 1,0,#last_op - official_rating) as decimal(10,2)) diff
from historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select #b:=0, #last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50
I want to hide
opening_position, last_opening_position
columns from the output result. My Mysql version 8.0.18
Use a subquery
select sf_name,finish_position,official_rating,date,bsp,diff from
(
select historic_betfair_win_prices.sf_name,historic_runners.finish_position,historic_runners.official_rating,historic_betfair_win_prices.date, historic_betfair_win_prices.bsp,
if(finish_position = 1 , #b:=#b+1,#b:=#b) opening_position,
if(finish_position = 1 , #last_op:=official_rating,#last_op:=#last_op)last_opening_position,
cast(if(#b = 0 or finish_position = 1,0,#last_op - official_rating) as decimal(10,2)) diff
from historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select #b:=0, #last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50
)A
select historic_betfair_win_prices.sf_name,
historic_runners.finish_position,
historic_runners.official_rating,
historic_betfair_win_prices.date,
historic_betfair_win_prices.bsp,
cast(if((#b := if(finish_position = 1 ,
#b+1,
#b))= 0 or finish_position = 1,
0,
(#last_op := if(finish_position = 1 ,
official_rating,
#last_op)) - official_rating) as decimal(10,2)) difffrom historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select #b:=0, #last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50

Different results from Identical databases

I'm having an issue where my live database (MariaDB) has the exact same data as my local(MySQL) but the following query is returning the same results but in a different order (I know im not the best at SQL so I'll apologise in advance):
SELECT
`products`.*
, CONCAT( `booking_inventory`.`year`, '-', LPAD( `booking_inventory`.`month`, 2, '00' ), '-', LPAD( `booking_inventory`.`day`, 2, '00' ) ) AS `order_date`
, `category_product`.`category_id` AS `pivot_category_id`
, `category_product`.`product_id` AS `pivot_product_id`
, `count_activate`.`active_count`
, IF( `count_activate`.`product_id` > 0, 0, 1 ) AS coming_soon
FROM
`products`
INNER JOIN
`category_product`
ON
`products`.`id` = `category_product`.`product_id`
LEFT JOIN
(
SELECT
inventory.*
FROM
inventory
INNER JOIN
`booking_inventory`
ON
`inventory`.`id` = `booking_inventory`.`inventory_id`
WHERE
CONCAT( `booking_inventory`.`year`, '-', LPAD( `booking_inventory`.`month`, 2, '00' ), '-', LPAD( `booking_inventory`.`day`, 2, '00' ) ) > NOW()
ORDER BY
DATE( CONCAT( `booking_inventory`.`year`, '-', LPAD( `booking_inventory`.`month`, 2, '00' ), '-', LPAD( `booking_inventory`.`day`, 2, '00' ) ) )
)
AS
inventory
ON
`products`.`id` = `inventory`.`product_id`
INNER JOIN
`booking_inventory`
ON
`inventory`.`id` = `booking_inventory`.`inventory_id`
LEFT JOIN
(
SELECT
COUNT(inventory.id) AS active_count
, product_id
FROM
inventory
INNER JOIN
`booking_inventory`
ON
`inventory`.`id` = `booking_inventory`.`inventory_id`
WHERE
status_id = 1
AND
(
stock > 0
OR stock = -1
)
AND
CONCAT( `booking_inventory`.`year`, '-', LPAD( `booking_inventory`.`month`, 2, '00' ), '-', LPAD( `booking_inventory`.`day`, 2, '00' ) ) > NOW()
GROUP BY
product_id
)
AS
count_activate
ON
`count_activate`.`product_id` = `products`.`id`
WHERE
`category_product`.`category_id` = 2
AND EXISTS
(
SELECT
*
FROM
`sites`
INNER JOIN
`product_site`
ON
`sites`.`id` = `product_site`.`site_id`
WHERE
`product_site`.`product_id` = `products`.`id`
AND
`status_id` = 1
AND
`site_id` = 1
)
AND
`products`.`status_id` = 1
AND
CONCAT( `booking_inventory`.`year`, '-', LPAD( `booking_inventory`.`month`, 2, '00' ), '-', LPAD( `booking_inventory`.`day`, 2, '00' ) ) > NOW()
GROUP BY
`products`.`id`
ORDER BY
`coming_soon` ASC
, `order_date` ASC
LIMIT 100
OFFSET 0
can anyone tell me whats causing this?
regards
(left id External right is Local)
EDIT
Thanks for the daft comments below and the down vote, very helpful.... After some digging, I have found the cause yet not the answer. In the second JOIN (inventory) the date ordering isn't returning the same results. If I order by the inventory id, price, SKU I get the same results across local and external data but not using the date... would anyone know why?
regards
The problem was down to the version/dbengine. The first left join has an order by in it, which I didn't realise didn't keep its order once used by the parent (depending on version/dbengine).
One way to overcome this is by setting a limit of 18446744073709551615 which forces the results to be stored in a temp table (or something, i know not what I speak!).
the other issue was inner join further down the query which forced to table to be reordered.
SELECT
IF( `counter`.`product_id` > 0, 0, 1 ) AS coming_soon,
bd.skill_level,
counter.active_count,
p.*
FROM
(
SELECT
p.*,
booking_inventory.inventory_id,
category_product.category_id,
CONCAT( `booking_inventory`.`year`, '-', LPAD( `booking_inventory`.`month`, 2, '00' ), '-', LPAD( `booking_inventory`.`day`, 2, '00' ) ) as date
FROM
booking_inventory
JOIN
inventory
ON
inventory.id = booking_inventory.inventory_id
LEFT JOIN
products AS p
ON
p.id = inventory.product_id
INNER JOIN
`category_product`
ON
`p`.`id` = `category_product`.`product_id`
WHERE
CONCAT( `booking_inventory`.`year`, '-', LPAD( `booking_inventory`.`month`, 2, '00' ), '-', LPAD( `booking_inventory`.`day`, 2, '00' ) ) > NOW()
AND
`category_product`.`category_id` = 2
ORDER BY
date
LIMIT
18446744073709551615
)
AS
p
LEFT JOIN
booking_data AS bd
ON
p.id = bd.product_id
LEFT JOIN
(
SELECT
COUNT(`inventory`.`id`) AS `active_count`,
`inventory`.`product_id`
FROM
`inventory`
INNER JOIN
`booking_inventory`
ON
`inventory`.`id` = `booking_inventory`.`inventory_id`
WHERE
`inventory`.`status_id` = 1
AND
(
`inventory`.`stock` > 0
OR
`inventory`.`stock` = -1
)
AND
CONCAT( `booking_inventory`.`year`, '-', LPAD( `booking_inventory`.`month`, 2, '00' ), '-', LPAD( `booking_inventory`.`day`, 2, '00' ) ) > NOW()
GROUP BY
`inventory`.`product_id`
)
AS
counter
ON
`counter`.`product_id` = `p`.`id`
WHERE
EXISTS
(
SELECT
*
FROM
`sites`
INNER JOIN
`product_site`
ON
`sites`.`id` = `product_site`.`site_id`
WHERE
`product_site`.`product_id` = `p`.`id`
AND
`status_id` = 1
AND
`site_id` = 1
)
GROUP BY
p.id
ORDER BY
coming_soon,
p.date,
p.name

How to perform multiple calculations with in a single query

I have a situation where in i have to get the data from an Year Ago , Previous Month and Current Month. What is the best way to achieve this ?
I have a table which contains the year,month and data in it. In the below query have added a filter
c.ReportMonth = DATENAME(month, #12MonthsAgo) and c.ReportYear = Year(#12MonthsAgo)
This is for an year ago. In the same way if i have to get the previous month and current month, can i do that with in the same query by setting the filters ? how do we do that ?
Is there a better way other than i end up writing 3 select queries and then putting the select to a tmp table and later merging the tables ?
create table #TPTABLE
(
KPIName varchar(150)
,MetricName Varchar(200)
,MetricId INT
,DataSource varchar(50)
,[AnYearAgo] Float
,[PreviousMonth] float
,[CurrentMonth] float
);
insert into #TPTABLE
(KPIName,MetricName,MetricId,DataSource,[AnYearAgo])
SELECT
p.KPIName
,p.MetricName
,p.MetricId
,p.DataSource
,c.Value as [AnYearAgo]
FROM [IntegratedCare].[report].[KPIMetricDetails] p
LEFT JOIN [IntegratedCare].[report].[KPIMectricValues] c
ON p.[MetricId] = c.MetricId
WHERE c.ReportMonth = DATENAME(month, #12MonthsAgo) and c.ReportYear = Year(#12MonthsAgo)
ORDER BY KPI_Id ASC, [MetricId] ASC
SELECT
p.KPIName
,p.MetricName
,p.MetricId
,p.DataSource
,c.Value
,c2.Value
,c3.Value
FROM [IntegratedCare].[report].[KPIMetricDetails] p
LEFT JOIN [IntegratedCare].[report].[KPIMectricValues] c
ON p.[MetricId] = c.MetricId
AND c.[CommissionerCode] = COALESCE(NULLIF(#Commissioner, ''), c.[CommissionerCode])
ANd ReportMonth = DATENAME(month, #12MonthsAgo) and c.ReportYear = Year(#12MonthsAgo)
LEFT JOIN [IntegratedCare].[report].[KPIMectricValues] c2
ON p.[MetricId] = c2.MetricId
AND c2.[CommissionerCode] = COALESCE(NULLIF(#Commissioner, ''), c2.[CommissionerCode])
ANd c2.ReportMonth = DATENAME(month, #PreviousMonth) and c2.ReportYear = Year(#PreviousMonth)
LEFT JOIN [IntegratedCare].[report].[KPIMectricValues] c3
ON p.[MetricId] = c3.MetricId
AND c3.[CommissionerCode] = COALESCE(NULLIF(#Commissioner, ''), c3.[CommissionerCode])
ANd c3.ReportMonth = DATENAME(month, #PreviousMonth) and c3.ReportYear = Year(#PreviousMonth)
ORDER BY p.KPI_Id ASC, p.[MetricId] ASC
I think what you need is this:
insert into #TPTABLE
(KPIName,MetricName,MetricId,DataSource,[AnYearAgo])
SELECT
KPIName
,MetricName
,MetricId
,DataSource
,[AnYearAgo]
,[PreviousMonth]
,[CurrentMonth]
FROM (
SELECT
KPIName
,MetricName
,MetricId
,DataSource
,KPI_Id
,sum(case when c.ReportMonth = DATENAME(month, #12MonthsAgo) and c.ReportYear = Year(#12MonthsAgo) then c.Value else 0 end) as [AnYearAgo]
,sum(case when c.ReportMonth = DATENAME(month, #PreviousMonth) and c.ReportYear = Year(#PreviousMonth) then c.Value else 0 end) as [PreviousMonth]
,sum(case when c.ReportMonth = DATENAME(month, #CurrentMonth) and c.ReportYear = Year(#CurrentMonth) then c.Value else 0 end) as [CurrentMonth]
FROM [IntegratedCare].[report].[KPIMetricDetails] p
LEFT JOIN [IntegratedCare].[report].[KPIMectricValues] c
ON p.[MetricId] = c.MetricId
GROUP BY KPIName, MetricName, MetricId, DataSource, KPI_Id
ORDER BY KPI_Id ASC, [MetricId] ASC

how to calculate from each row value in sql

I have a table named general_ledger from which I need to show dr_amount, cr_amount and the balance between them as running_balance. That's why I have written a query that is given below. But I am getting the result of each query like the balance only of current row. But I need to produce the result with the remaining balance. Suppose First row dr_balance is 20000 and cr_balance is 5000 and remaining balance is 15000. In second row only cr_balance is 5000. Now the result should be 10000 with the deduction but my result is -5000. I have no idea how to fix this. Can anyone please help me on this? I need your help very much. Here is my query given below :
SELECT '' AS cost_center_id
, '' AS cost_center_name
, '' AS office_code
, CONVERT('2013-02-01',DATETIME) AS transaction_date
, '' AS accounts_head_id
, '' AS account_name
, '' AS opposite_accounts_head_id
, '' AS opposite_account_name
, 'Opening Balance' AS particulars
, tempOpeningBalance.dr_amount
, tempOpeningBalance.cr_amount
, '' AS voucher_no
, '' AS vin
FROM (SELECT IFNULL(mcoa.account_code,'1101010101100321') AS account_code
, IFNULL(mcoa.account_name,'Cash') AS account_name
, IFNULL(mcoa.account_type,'ASSET') AS accountType
, CAST(IFNULL(SUM(IFNULL(maingl.dr_balance,0)),0) AS DECIMAL(27,5)) AS dr_amount
, CAST(IFNULL(SUM(IFNULL(maingl.cr_balance,0)),0) AS DECIMAL(27,5)) AS cr_amount
FROM master_chart_of_accounts AS mcoa
INNER JOIN chart_of_accounts AS coa ON (mcoa.id = coa.master_chart_of_accounts_id AND mcoa.id = 80)
LEFT JOIN general_ledger AS maingl ON (coa.id = maingl.accounts_head_id AND coa.account_code='1101010101100321')
INNER JOIN
( SELECT gl.accounts_head_id, MAX(gl.gl_id) AS max_gl_id, gl.office_code, gl.office_type, gl.country_id,gl.cost_center_id
FROM general_ledger AS gl
-- INNER JOIN voucher_info AS vi ON (gl.voucher_info_id = vi.id)
-- WHERE vi.posting_date < '2013-02-01' AND
WHERE gl.transaction_date < '2013-02-01' AND
gl.cost_center_id IN ('BI0000000000000000000001') AND
gl.country_id IN (1) AND
gl.office_code IN ('UG500013') AND
1=1
GROUP BY gl.accounts_head_id, gl.office_code, gl.office_type, gl.country_id,gl.cost_center_id
ORDER BY gl.accounts_head_id
) AS tmpgl
ON ( maingl.office_code = tmpgl.office_code
AND maingl.office_type = tmpgl.office_type
AND maingl.accounts_head_id = tmpgl.accounts_head_id
AND maingl.country_id = tmpgl.country_id
AND maingl.cost_center_id = tmpgl.cost_center_id
AND maingl.gl_id = tmpgl.max_gl_id
)
WHERE mcoa.account_status_id = 1 AND
coa.account_status_id = 1
) AS tempOpeningBalance
UNION
SELECT vi.cost_center_id
, cc.center_name AS cost_center_name
, gl.office_code
, vi.posting_date AS transaction_date
, vd.accounts_head_id
, (SELECT chart_of_accounts.account_name FROM chart_of_accounts WHERE chart_of_accounts.id = vd.accounts_head_id) AS account_name
, vd.opposite_accounts_head_id
, (SELECT chart_of_accounts.account_name FROM chart_of_accounts WHERE chart_of_accounts.id = vd.opposite_accounts_head_id) AS opposite_account_name
, vd.particulars
, gl.dr_amount AS dr_amount -- here to check
, gl.cr_amount AS cr_amount
, vi.voucher_no
, vi.vin
FROM general_ledger AS gl
INNER JOIN voucher_info AS vi
ON (gl.voucher_info_id = vi.id)
INNER JOIN cost_center AS cc
ON (vi.cost_center_id = cc.id)
INNER JOIN voucher_details AS vd
ON (vi.id = vd.voucher_info_id)
INNER JOIN chart_of_accounts AS coa
ON (vd.accounts_head_id = coa.id)
WHERE vi.posting_date BETWEEN '2013-02-01' AND'2013-02-28'
AND vi.voucher_status_id = 3
AND vd.status_id = 1
AND vi.office_code = 'UG500063'
AND coa.account_code='1101010101100321'
AND coa.cost_center_id = 'BI0000000000000000000001'
ORDER BY cost_center_name
, office_code
, transaction_date;
Use a variable like this
SET #running_balance=0;
SELECT dr_amount AS dr_amount
, cr_amount AS cr_amount
, #running_balance := (#running_balance + dr_amount - cr_amount)
FROM general_ledger