Access Calculated fields if statement - ms-access

Is it possible to have a calculated field where some of the columns are not calculated?
with not calculated I mean that some of the data needs to be calculated and some of the data needs to be put in by hand
I have already tried it with an IIF statement like this
IIf( [Uitkomst] = 0 , [Lengte] * [Breedte] * [Hoogte] , [Uitkomst])

If you by "not calculated" mean Null, you can use Nz for these empty fields:
IIf([Uitkomst] = 0, Nz([Lengte]) * Nz([Breedte]) * Nz([Hoogte]), [Uitkomst])
Query:
Select
*, IIf([Uitkomst] = 0, [Lengte] * [Breedte] * [Hoogte], [Uitkomst])
From
YourTable

Related

How to Implement a if clause when the result of a calculation is less then zero

THE CODE I AM WORKING IS:
UPDATE `tab_base_asset`
INNER JOIN `vw_calcula_taxa_adm_ymf_acumulada_3`
ON `tab_base_asset`.`codigo_fundo` = `vw_calcula_taxa_adm_ymf_acumulada_3`.`codigo_fundo`
SET `tab_base_asset`.`RECEITA_ADM_YMF` = (`tab_base_asset`.`saldo_bruto_cdc`/`vw_calcula_taxa_adm_ymf_acumulada_3`.`saldo_bruto_cdc`) * `vw_calcula_taxa_adm_ymf_acumulada_3`.`receita_YMF_ACUM`,
`tab_base_asset`.`RECEITA_REBATE` = (`tab_base_asset`.`saldo_bruto_cdc`/`vw_calcula_taxa_adm_ymf_acumulada_3`.`saldo_bruto_cdc`) * `vw_calcula_taxa_adm_ymf_acumulada_3`.`Rebate_acumulado`
WHERE `tab_base_asset`.`data` = (SELECT `tab_aux_datas_base_unica`.`data_final` FROM `tab_aux_datas_base_unica`);
I would like to make the column receita_adm_ymf to become 0 for values which are less then 0.
I have got some syntax errors when using IF on My SQL Workbench 5.2 I also tried Case but I am not sure where to place it in the code.
Use the GREATEST() function to assign the max of the expression value and zero.
SET `tab_base_asset`.`RECEITA_ADM_YMF` = GREATEST(0, (`tab_base_asset`.`saldo_bruto_cdc`/`vw_calcula_taxa_adm_ymf_acumulada_3`.`saldo_bruto_cdc`) * `vw_calcula_taxa_adm_ymf_acumulada_3`.`receita_YMF_ACUM`),

CASE inside IF() function in raw SQL query

I have a SQL query which already uses an IF() function to check some conditions on basis of which respective expression is returned. I have to add another condition (which will be another 'and') inside the IF() which will affect the attributes from both the expressions. The query is,
select
#{booking_variable}.travel_id as operator_id,
round(sum(#{ticket_variable}.customer_commission), 2) as commission,
IF(
(#{booking_variable}.is_online = #{AdminType::YES}
and #{booking_variable}.is_ts_payment = #{AdminType::YES}),
round(sum(-#{ticket_variable}.customer_commission
- #{ticket_variable}.convenience_charge_amount
+ #{ticket_variable}.our_convenience_charge_amount), 2),
round(sum(#{ticket_variable}.adult_fare
- #{ticket_variable}.customer_commission
+ #{ticket_variable}.service_tax_amount
+ #{ticket_variable}.our_convenience_charge_amount
- #{ticket_variable}.offer_discount), 2)
) as amount_to_be_paid,
round(sum(#{booking_variable}.total_fare)) as total_fare,
0 as cancel_fare,
round(sum(#{ticket_variable}.adult_fare
+ #{ticket_variable}.service_tax_amount
- #{ticket_variable}.offer_discount )) as net_amount,
#{booking_variable}.travel_name as operator_name,
ROUND(sum(#{ticket_variable}.service_tax_amount), 2) as total_service_tax,
ROUND(sum(#{ticket_variable}.convenience_charge_amount), 2) as total_convenience_charge_amount,
ROUND(sum(#{ticket_variable}.our_convenience_charge_amount), 2) as total_our_convenience_charge_amount,
0 as cancelled_convenience_charge_amount,
(select users.branch_id from users where id=#{ticket_variable}.booked_by) as travel_branch_id
from #{booking_variable} use index(index_#{booking_variable}_travel_date),
#{ticket_variable}
where #{conditions1[0]}
group by travel_branch_id, operator_id
Here, inside the IF() expression, I have to check another variable's value . If the value is true, then the query should run as is, if not, the value of #{ticket_variable}.convenience_charge_amount + #{ticket_variable}.our_convenience_charge_amount and #{ticket_variable}.our_convenience_charge_amount is to be taken as 0.
Any help appreciated.
You can nest IF() expressions.
If you need part of your calculation to be conditional, you can use an IF() for that.
...
IF(
(#{booking_variable}.is_online = #{AdminType::YES}
and #{booking_variable}.is_ts_payment = #{AdminType::YES}),
round(sum(-#{ticket_variable}.customer_commission
- IF((...some other condition...),
#{ticket_variable}.convenience_charge_amount
+ #{ticket_variable}.our_convenience_charge_amount,
0)
), 2),
...

MySQL query works as normal SELECT but not inside CREATE TABLE AS..?

I'm trying to figure out why this query SELECTs just fine, but I can't use it to create a temporary table... The IF = '', 0 stuff didn't used to exist in the original query so I added it to make sure that I wasn't trying to sum anything that could potentially be an empty string, but it didn't fix the problem. This select works and returns the correct result set:
SELECT
SUM(((IF(reserve_transactions.Revenue = '',
0,
reserve_transactions.Revenue) * IF(reserve_transactions.Confidence = '',
0,
reserve_transactions.Confidence)) / 100)) AS rawadjusted
FROM
(store_locations
LEFT JOIN reserve_transactions ON ((store_locations.ID = location_sales)))
GROUP BY store_locations.Loc_Long
But this does not:
CREATE TEMPORARY TABLE tmptable_which_doesnt_work AS SELECT
SUM(((IF(reserve_transactions.Revenue = '',
0,
reserve_transactions.Revenue) * IF(reserve_transactions.Confidence = '',
0,
reserve_transactions.Confidence)) / 100)) AS rawadjusted
FROM
(store_locations
LEFT JOIN reserve_transactions ON ((store_locations.ID = location_sales)))
GROUP BY store_locations.Loc_Long
The error is: Error Code: 1292. Truncated incorrect DECIMAL value: ''
I have other queries where the situation is the same, actually. Sometimes with other truncated incorrect types. What am I missing here?
I think that the problem could be data and the logic of selecting only the numeric entries - You could try to define a functions as follows:
CREATE FUNCTION IsNumeric (sIn varchar(1024))
RETURNS tinyint
RETURN sIn REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$';
and apply it in the where clause for the two arguments, eventually trim unnecessary white spaces (as per How do I check to see if a value is an integer in MySQL? )

Totaling an expression in SSRS

I have an expression that calculates a value in a textbox. I would like, at the end of the report, to have a total of all the fields in that textbox. However, the expression uses named fields from the query, which are totaled also.
=SUM(Fields!Total_Defective__.Value) / SUM(Fields!sales_Dollars.Value)
Total_Defective__ and sales_Dollars are totaled at the end of the report. So when I put that expression in the total field for that column, it performs the calculation on the totals for the other columns. This produces a incorrect result, since its based on the totals of the other fields. what I'm trying to do is sum the column. I tried Use a summary field in an expression in SSRS reports but this only gives me the row above the total, and you cannot aggregate by it.
So the report looks like this:
The COQ total colummn is taking the total of Defective $ / sales. I would like it to add the column (COQ) to be $0.39
Here is what the query looks like:
--Prod Qty
SELECT Division as 'division', SUM(prodtable.qtysched)as 'qty',rtrim(Ltrim(itemgroupid)) as 'itemGroup'
into #SCHED
FROM MiscReportTables.dbo.PlantDivisions
inner join prodtable on prodtable.dimension2_ = MiscReportTables.dbo.PlantDivisions.Division
WHERE PlantID IN (#plantid)
and SCHEDDATE between #start and #end
Group by itemgroupid,MiscReportTables.dbo.PlantDivisions.Division
--sales qty
Select Division as 'Division', SUM(SALESQTY) as 'salesQTY',rtrim(Ltrim(salesline.itemgroupid)) as 'itemGroup'
into #salesQty
FROM MiscReportTables.dbo.PlantDivisions
inner join prodtable on prodtable.dimension2_ = MiscReportTables.dbo.PlantDivisions.Division
inner join SalesLine on SalesLine.InventrefId = ProdTable.ProdiD
WHERE PlantID IN (#plantid)
and SCHEDDATE between #start and #end
Group By Division,salesLine.itemgroupid
--SALES Dollars
Select Division as 'Division',
(SUM(SALESQTY) - REMAINSALESFINANCIAL) * (SalesPrice / PriceUnit) as 'sales$',
rtrim(Ltrim(salesline.itemgroupid)) as 'itemGroup'
into #salesDollars
FROM MiscReportTables.dbo.PlantDivisions
inner join prodtable on prodtable.dimension2_ = MiscReportTables.dbo.PlantDivisions.Division
inner join SalesLine on SalesLine.InventrefId = ProdTable.ProdiD
WHERE PlantID IN (#plantid)
and SCHEDDATE between #start and #end
Group By Division,salesLine.itemgroupid,REMAINSALESFINANCIAL,SalesPrice,PriceUnit
SELECT
dbo.TQMNCR.NCRID,
dbo.TQMPlantTable.PlantName AS 'Division',
RTRIM(LTRIM(dbo.INVENTTABLE.ITEMGROUPID)) AS 'Item Process/Group',
dbo.TQMNCRDEFECTTYPECODES.QTY AS 'Defective Qty',
CASE CATYPE
WHEN 0 THEN
(CASE WHEN dbo.SALESLINE.SALESID = ''
THEN ISNULL((PRICE * (PERCENTEXT / 100)) / NULLIF(dbo.INVENTTABLEMODULE.PRICEUNIT, 0), 0) * dbo.TQMNCRDEFECTTYPECODES.QTY
ELSE ISNULL((SALESPRICE * (PERCENTEXT / 100)) / NULLIF(dbo.SALESLINE.PRICEUNIT, 0), 0) * dbo.TQMNCRDEFECTTYPECODES.QTY END)
WHEN 2 THEN
(CASE WHEN dbo.TQMNCR.SALESID = ''
THEN ISNULL((PRICE * (PERCENTINT / 100)) / NULLIF(dbo.INVENTTABLEMODULE.PRICEUNIT, 0), 0) * dbo.TQMNCRDEFECTTYPECODES.QTY
ELSE ISNULL((SALESPRICE * (PERCENTINT / 100)) / NULLIF(dbo.SALESLINE.PRICEUNIT, 0), 0) * dbo.TQMNCRDEFECTTYPECODES.QTY END)
ELSE 0 END AS 'Total Defective $',
dbo.PRODTABLE.PRODPOOLID
,#SCHED.qty,
(#SCHED.qty - dbo.TQMNCRDEFECTTYPECODES.QTY) / #SCHED.qty as 'First Pass Yield',
#salesQty.salesQty as 'Sales Quantity',
#salesDollars.sales$ as 'sales Dollars'
FROM
dbo.TQMNCR LEFT OUTER JOIN
dbo.TQMDISPOSITION ON dbo.TQMNCR.DISPOSITIONID = dbo.TQMDISPOSITION.DISPOSITIONID LEFT OUTER JOIN
dbo.TQMCA_TABLE ON dbo.TQMCA_TABLE.NCRID = dbo.TQMNCR.NCRID LEFT OUTER JOIN
dbo.TQMNCRDEFECTTYPECODES ON dbo.TQMNCR.NCRID = dbo.TQMNCRDEFECTTYPECODES.NCRID LEFT OUTER JOIN
dbo.TQMPlantTable ON TQMPlantTable.PlantID = dbo.TQMNCR.PlantID LEFT OUTER JOIN
dbo.INVENTTABLE ON dbo.TQMNCR.ITEMID = dbo.INVENTTABLE.ITEMID LEFT OUTER JOIN
dbo.INVENTTABLEMODULE ON dbo.INVENTTABLE.ITEMID = dbo.INVENTTABLEMODULE.ITEMID AND MODULETYPE = 2 LEFT OUTER JOIN
dbo.SALESLINE ON dbo.SALESLINE.SALESID = dbo.TQMNCR.SALESID AND dbo.SALESLINE.ITEMID = dbo.TQMNCR.ITEMID LEFT OUTER JOIN
dbo.PRODTABLE ON dbo.TQMNCR.PRODID = dbo.PRODTABLE.PRODID
inner join #sched on #sched.itemGroup = INVENTTABLE.itemgroupid
inner join #salesQty on #salesQty.itemGroup = INVENTTABLE.itemgroupid
inner join #salesDollars on #salesDollars.itemgroup = INVENTTABLE.itemgroupid
WHERE
SCHEDDATE between #start and #end
AND
dbo.TQMNCR.PlantID IN (#plantid)
ORDER BY dbo.INVENTTABLE.ITEMGROUPID, dbo.TQMPlantTable.PlantName
drop table #sched
drop table #SalesQty
drop table #salesDollars
and here's what the result set looks like:
The report is grouped by Item_Process,Division,Total_Defective
You could try adding your COQ field as a new Calculated Field in your dataset. Doing this will perform the calculation at dataset level, rather than Tablix grouping level.
Lets say you've called this new field "COQ".
Then in your total row, have the expression Sum(Fields!COQ.Value) as your total.
This should perform the calculation for each row's COQ first, then sum the result in the total row.
EDIT: The above will work if your dataset were grouped exactly as your table will be. When this is not the case (as you've indicated) and your table in SSRS is actually grouped from a more granular dataset, you can total your groups using the expression below:
=Sum(IIF(Sum(Fields!sales_Dollars.Value,"YOURGROUPNAME") > 0,
Sum(Fields!Total_Defective__.Value,"YOURGROUPNAME") /
Sum(Fields!sales_Dollars.Value,"YOURGROUPNAME"), 0))
This should evaluate the calculation within each member of the GROUP BY, and then SUM the result of the calculation across the entire table/dataset.
I beleive your requirement is beyond the capabilities of SSRS alone. I would move the grouping to the SQL dataset and (after grouping to the 9 "detail" rows in your example) I would calculate COQ in that dataset e.g.
SELECT *
, Total_Defective / Sales AS COQ
FROM (
SELECT
MyGroupColumns
, SUM ( Total_Defective ) AS Total_Defective
, SUM ( Sales ) AS Sales
FROM MyTable
GROUP BY
MyGroupColumns
) D1
Then SSRS can just present the detail COQ for the 9 rows output from the dataset, and you can use an SSRS Sum() function to get COQ for your Total row.
You should be able to do this with
=SUM(Fields!Total_Defective__.Value/Fields!sales_Dollars.Value)
So that it divides each value, then sums rather than summing the values before dividing.
EDIT: if you get divide by zero errors you can add the following to Report - Report Properties - code:
Public Function Quotient(ByVal numerator As Decimal, denominator As Decimal) As Decimal
If denominator = 0 Then
Return 0
Else
Return numerator / denominator
End If
End Function
(Ref: http://williameduardo.com/development/ssrs/ssrs-divide-by-zero-error/)
The enter the formula as
=SUM(code.Quotient(Fields!Total_Defective__.Value,Fields!sales_Dollars.Value)
Then you should get the desired result with relatively short code in your expression.

MDX report rendering slow

This is my MDX query:
with member [Measures].[Rent] as IIF(IsEmpty([Measures].[Budget]), NULL, [Measures].[Rent])
select {[Measures].[Rent]} on columns,
[Property].[Address].[All].children *
DESCENDANTS([Account].[Account Hierarchy].[Account Group].[Expenditures],
[Account].[Account Tree].[Account]) *
[Asset].[asset].[All].children on rows
from [Master]
When I comment the [Asset] Dimension member, I get the result, but I need Asset Dimension in MDX.
Does anyone have an idea on what to do??
You should try filtering dimensions before crossjoining them. In your case, if budget is null, just leave it. Also don't forget to add NON EMPTY clause to remove empty values from result set:
with
member hasBudget as
(
IIF(IsEmpty([Measures].[Budget]), 0, 1)
)
member [Rent] as IIF(IsEmpty([Measures].[Budget]), NULL, [Measures].[Rent])
set accounts = Filter(DESCENDANTS([Account].[Account Hierarchy].[Account Group].[Expenditures],[Account].[Account Tree].[Account]), [Measures].[hasBudget] = 1)
select non empty
{ [Measures].[Rent] } on 0,
non empty
{ ([accounts] * (EXISTING [Asset].[asset].[All].children) * (EXISTING [Property].[Address].[All].children)) } on 1
from ( select { Filter([Asset].[asset].[All].children, [Measures].[hasBudget] = 1) } on 0
from ( select { Filter([Property].[Address].[All].children, [Measures].[hasBudget] = 1) } on 0
from [Master]))