CASE statement not updating Temp Table - sql-server-2008

In the UPDATE statement below, the InspectionChg, MileageChg, FuelChg and FreightChg columns are not updating to temp table. Goal is to aggregate charges. I have tried several variations and I cannot get Temp Table Columns to update.
UPDATE #TTable
SET ChargeCode = id.cht_itemcode,
InspectionChg = CASE WHEN LEFT(id.cht_itemcode, 3) = 'INS' THEN
InspectionChg+id.ivd_charge ELSE InspectionChg+0 END,
MileageChg = CASE WHEN LEFT(id.cht_itemcode, 4) = 'MILE' THEN MileageChg+id.ivd_charge
ELSE MileageChg+0 END,
FuelChg = CASE WHEN LEFT(id.cht_itemcode, 4) = 'FUEL' THEN
FuelChg+id.ivd_charge ELSE FuelChg+0 END,
FreightChg = CASE WHEN LEFT(id.cht_itemcode, 2) = 'LH' THEN FreightChg+id.ivd_charge
ELSE FreightChg+0 END,
Rate = 1
FROM #TTable
INNER JOIN invoicedetail as id
on #TTable.OrderNumber = id.Ord_hdrnumber
What is wrong?

UPDATE TT
SET TT.ChargeCode = id.cht_itemcode ,
TT.InspectionChg = ( CASE WHEN LEFT(id.cht_itemcode, 3) = 'INS'
THEN InspectionChg + id.ivd_charge
ELSE InspectionChg + 0
END ) ,
TT.MileageChg = ( CASE WHEN LEFT(id.cht_itemcode, 4) = 'MILE'
THEN MileageChg + id.ivd_charge
ELSE MileageChg + 0
END ) ,
TT.FuelChg = ( CASE WHEN LEFT(id.cht_itemcode, 4) = 'FUEL'
THEN FuelChg + id.ivd_charge
ELSE FuelChg + 0
END ) ,
TT.FreightChg = ( CASE WHEN LEFT(id.cht_itemcode, 2) = 'LH'
THEN FreightChg + id.ivd_charge
ELSE FreightChg + 0
END ) ,
TT.Rate = 1
FROM #TTable AS TT
INNER JOIN invoicedetail AS id ON TT.OrderNumber = id.Ord_hdrnumber

Related

MYSQL Group by DATA NOT individually

This is My Data:
I want select data Like This ▼
I try select that in group by but is not individually data show.
and this is my code
select
date_format((select receive_contract_datetime from worklist_info where id = worklist_id), '%y.%m.%d') as receive_datetime,
(select trade_name from trade_info where id = (select worklist_trade_id from worklist_info where id = worklist_id)) as trade_name,
(select staff_name from staff_info where id =
(select account_staff_id from account_info where id =
(select worklist_account_id from worklist_info where id = worklist_id))) as worklist_writer,
date_format((select worklist_output_plan_date from worklist_info where id = worklist_id), '%y.%m.%d') as output_plan_date,
(select worklist_project_name from worklist_info where id = worklist_id) as prj_name,
worklist_sub_process_id,
count(worklist_sub_process_id),
sum(worklist_sub_state),
-- (sum(worklist_sub_process_id = 1)*2) as laser_count, worklist_sub_state
-- sum(worklist_sub_process_id = 1) as laser_count,
-- if(sum(worklist_sub_process_id = 1) > 0,count(IF(worklist_sub_process_id = 1, if(worklist_sub_state = 0,1,null), null)),-1) as laser_wait,
-- if(sum(worklist_sub_process_id = 1) > 0,count(IF(worklist_sub_process_id = 1, if(worklist_sub_state = 1,1,null), null)),-1) as laser_run,
-- if(sum(worklist_sub_process_id = 1) > 0,count(IF(worklist_sub_process_id = 1, if(worklist_sub_state = 2,1,null), null)),-1) as laser_end,
(select worklist_comment from worklist_info where id = worklist_id) as worklist_comment,
(select worklist_lot from worklist_info where id = worklist_id) as lot_number
from worklist_info_sub group by worklist_id,worklist_sub_process_id;
You seem to pivot your dataset. For this, you can use conditional aggregation:
select col_master_id,
sum(col_semi_id = 1) as col_semi_1_count,
sum(case when col_semi_id = 1 then col_state else 0 end) as col_semi_1_state,
sum(col_semi_id = 2) as col_semi_2_count,
sum(case when col_semi_id = 2 then col_state else 0 end) as col_semi_2_state,
sum(col_semi_id = 3) as col_semi_3_count,
sum(case when col_semi_id = 3 then col_state else 0 end) as col_semi_3_state,
from mytable
group by col_master_id
I don't see how your query relates to your data. This answer is based on your sample data and desired results, not on your query.

sum function based on unique date

actually i want a total value based on unique date
SELECT t2.stateName,
t3.`districtName`,t1.fingerDate,COUNT(a.arg1),COUNT(a.arg2),COUNT(a.arg3),COUNT(a.arg4),COUNT(a.arg5),COUNT(a.arg6),COUNT(a.arg7), COUNT(a.arg8),(COUNT(a.arg1) + COUNT(a.arg2) + COUNT(a.arg3) + COUNT(a.arg4) + COUNT(a.arg5) + COUNT(a.arg6) + COUNT(a.arg7))AtotalScreeningArg
FROM tbl_user AS t1
LEFT JOIN tbl_state AS t2 ON t1.addressState = t2.stateId
LEFT JOIN `tbl_district` AS t3 ON t1.addressDistrict = t3.`districtId`
LEFT JOIN (SELECT userId,
CASE WHEN occupation = "Truckers" OR occupation = "Drivers"
THEN occupation END arg1,
CASE WHEN (occupation = "Migrant")
THEN occupation END arg2,
CASE WHEN (hrg IS NULL OR hrg = " ") AND (`arg` IS NULL OR `arg` = " ")
THEN "Student" END arg3,
CASE WHEN (occupation = "Daily Wage")
THEN occupation END arg4,
CASE WHEN (occupation = "Salaried" OR occupation = "self Employed" OR occupation ="Unemployed" OR occupation = "Other")
THEN occupation END arg5,
CASE WHEN (ARG = "Female Partner (FPHRG)" OR ARG = "Partner / Spouse of FSW")
THEN ARG END arg6,CASE WHEN ARG = "Female Partner (FPARG)" THEN ARG END arg7,
CASE WHEN ARG = "TG (F-M)" THEN ARG END arg8,CASE WHEN hrg = "MSM" THEN hrg END arg9,
CASE WHEN hrg = "TG(M_F)" THEN hrg END arg10,CASE WHEN hrg = "FSW" THEN hrg END arg11,CASE WHEN hrg = "IDU" THEN hrg END arg12 FROM `tbl_user`
WHERE fingerDate IS NOT NULL OR fingerDate != " ")a ON t1.userId = a.userId
WHERE `t1`.`deleted` = "N" AND t1.userType = "user" AND `t1`.`fingerDate` >= '2018-11-01' AND `t1`.`fingerDate` <= '2018-12-01' AND t1.addressState = '34' AND t1.addressDistrict = '614' GROUP BY t1.userId
it gives result but not for unique date

not retrieving exact result from case statement

I am using below query but Y column not retrieving exact result. Could you guys please help me out
SELECT FAPI.*,
CASE WHEN (SELECT DISTINCT 'Y'
FROM FLOOR_PI FAPI,
NUATON NUMF
WHERE FAPI.BRCH = NUMF.BRCH
AND FAPI.BASE = NUMF.BASE
AND FAPI.NUM = 0
AND NVL(FAPI.RATION, 'X') <> 'D'
AND FAPI.CODE = 'A'
AND NUMF.R_DATE
BETWEEN FAPI.EFF_DATE
AND FAPI.EXP_DATE ) = 'Y'
THEN 'Y'
ELSE 'N' END NEW
FROM FLOOR_PI FAPI
Thank you,
Rave
Based on #SlimsGohst comment:
You should replace FAPIx with FAPI1 or FAPI2 whichever is applicable
SELECT FAPI1.*,
CASE WHEN (SELECT DISTINCT 'Y'
FROM FLOOR_PI FAPI2,
NUATON NUMF
WHERE FAPIx.BRCH = NUMF.BRCH
AND FAPIx.BASE = NUMF.BASE
AND FAPIx.NUM = 0
AND NVL(FAPIx.RATION, 'X') <> 'D'
AND FAPIx.CODE = 'A'
AND NUMF.R_DATE
BETWEEN FAPIx.EFF_DATE
AND FAPIx.EXP_DATE ) = 'Y'
THEN 'Y'
ELSE 'N' END NEW
FROM FLOOR_PI FAPI1

Tuning Slow Performing Queries

I have a query which is taking too long to execute.
I used database tuning advisor to check this query and it suggested some missing indexes and statistics. The problem is I can't create missing index and statistics on those tables because it will slowdown insert/update and affect other scripts. They can't sacrifice their scripts performance because of my query.
Without the help of DTA or disturbing other scripts how do I have to tune my query? Can i break it into small pieces? If so, how?
INSERT INTO #val
SELECT lid.orgid,
lid.periodid,
lid.sourceid,
lid.statementtypecode,
lid.financialsbucketid,
lid.statementcurrencycodeiso,
lid.lineitemid,
lll.financialconceptidglobal,
lid.physicalmeasureid,
CASE
WHEN EXISTS(SELECT TOP 1 '1'
FROM trf.dbo.lineitemfundbdescription LIFD(nolock)
WHERE lll.orgid = lifd.orgid
AND lll.lineitemid = lifd.lineitemid) THEN
(SELECT lifd.lineitemshortdescription
FROM trf.dbo.lineitemfundbdescription LIFD(nolock)
WHERE lll.orgid = lifd.orgid
AND lll.lineitemid = lifd.lineitemid)
ELSE lll.lineitemname
END AS LineItemName,
( CASE
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND
lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 1 ) THEN
lid.lineiteminstancevalue *
cds.dbo.Exrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso, p.periodenddate)
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 0
AND p.periodlengthunitcode = 'M' ) THEN lid.lineiteminstancevalue
*
cds.dbo.Getaveragefxrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso,
Dateadd("MONTH", -p.periodlength, p.periodenddate), p.periodenddate)
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 0
AND p.periodlengthunitcode = 'W' ) THEN lid.lineiteminstancevalue
*
cds.dbo.Getaveragefxrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso,
Dateadd("WEEK", -p.periodlength, p.periodenddate), p.periodenddate)
ELSE lid.lineiteminstancevalue
END ) AS LineItemInstanceValue,
( CASE
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 1 ) THEN
lid.adjustedforcorporateactionvalue *
cds.dbo.Exrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso, p.periodenddate)
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 0
AND p.periodlengthunitcode = 'M' ) THEN
lid.adjustedforcorporateactionvalue
*
cds.dbo.Getaveragefxrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso,
Dateadd("MONTH", -p.periodlength, p.periodenddate), p.periodenddate)
WHEN ( lid.reportedcurrencycodeiso IS NOT NULL
AND fc.iscurrencydependent = 1
AND lid.statementcurrencycodeiso <> lid.reportedcurrencycodeiso
AND fc.isflowitem = 0
AND p.periodlengthunitcode = 'W' ) THEN
lid.adjustedforcorporateactionvalue
*
cds.dbo.Getaveragefxrate(lid.reportedcurrencycodeiso, lid.statementcurrencycodeiso,
Dateadd("WEEK", -p.periodlength, p.periodenddate), p.periodenddate)
ELSE lid.adjustedforcorporateactionvalue
END ) AS AdjustedForCorporateActionValue,
lid.reportedcurrencycodeiso,
lid.xbrlelementid,
xbrlele.xbrlelementname,
Cast(NULL AS CHAR(3)),
Cast(NULL AS DATETIME),
Cast(NULL AS DATETIME),
Cast(NULL AS CHAR(1)),
Cast(NULL AS DATETIME),
Cast(NULL AS SMALLINT),
src.dcn,
src.docformat,
lid.asreporteditemid,
ari.docbyteoffset,
ari.docbytelength,
ari.bookmark,
ari.itemdisplayednegativeflag,
ari.itemscalingfactor,
ari.itemdisplayedvalue,
ari.reportedvalue,
ari.reporteddescription,
ari.editeddescription,
src.documentid,
lid.isderived,
lid.statementsectioncode,
IsMissMatchPhysicalMeasureID =0,
lid.istotal,
lid.isexcludedfromstandardization,
si.isdetailed AS IsDetailedSection,
si.ispreliminary AS IsPreliminary,
IsCreditSection =Cast(NULL AS BIT),
IsCreditFCC =Cast(NULL AS BIT),
si.isproforma,
lll.instrumentndaid,
InterimTypeID = CASE p.periodicitycode
WHEN 'A' THEN 0
WHEN 'S' THEN 2
WHEN 'T' THEN 3
WHEN 'Q' THEN 4
END,
si.isnotcomparabletopriorperiod,
si.isfundbspecial,
si.isderived AS IsDerivedSI,
lid.systemderivedtypecode
--FBLog.tasktypeid,
--FBLog.systemstartdatetime,
--FBLog.issplit
FROM trf.dbo.lineiteminstance LID(nolock)
--INNER JOIN #fundbbackwardlog FBLog
-- ON FBLog.orgid = lid.orgid
-- AND FBLog.periodid = lid.periodid
-- AND FBLog.sourceid = lid.sourceid
-- AND FBLog.statementtypecode = lid.statementtypecode
-- AND FBLog.financialsbucketid = lid.financialsbucketid
-- AND FBLog.statementcurrencycodeiso =
-- lid.statementcurrencycodeiso
-- AND lid.asreporteditemid IS NOT NULL
-- AND lid.lineiteminstanceasreporteditemid IS NULL
INNER JOIN trf.dbo.statementinstance SI(nolock)
ON lid.orgid = si.orgid
AND lid.periodid = si.periodid
AND lid.sourceid = si.sourceid
AND lid.statementtypecode = si.statementtypecode
AND lid.financialsbucketid = si.financialsbucketid
AND lid.statementcurrencycodeiso = si.statementcurrencycodeiso
INNER JOIN trf.dbo.period P(nolock)
ON lid.orgid = p.orgid
AND lid.periodid = p.periodid
INNER JOIN trf.dbo.lineitem LLL(nolock)
ON lll.orgid = lid.orgid
AND lll.lineitemid = lid.lineitemid
INNER JOIN trf.dbo.financialconcept FC(nolock)
ON lll.financialconceptidglobal = fc.financialconceptid
LEFT OUTER JOIN trf.dbo.xbrlelement XBRLEle(nolock)
ON lid.xbrlelementid = xbrlele.xbrlelementid
INNER JOIN trf.dbo.asreportedinstance ARI(nolock)
ON lid.orgid = ari.orgid
AND lid.sourceid = ari.sourceid
AND lid.asreporteditemid = ari.asreporteditemid
INNER JOIN trf.dbo.[source] SRC(nolock)
ON src.orgid = ari.orgid
AND src.sourceid = ari.sourceid
WHERE ari.reportedvalue IS NOT NULL --AND SRC.DCN > '' --AND SRC.DocFormat > '' --AND ARI.BookMark > ''
Try to remove functions called in the query like : Exrate() and Getaveragefxrate().
Also change the case statement, where you are using subquery as following.
In the end of the query, use
left outer join trf.lineitemfundbdescription lifd
on lll.orgid = lifd.orgid and lll.lineitemid = lifd.lineitemid
and then the case will be changed to
case
when lifd.orgid is null then lll.lineitemname
else lifd.lineitemshortdescription End As LineItemName
It will fine tune your query to a level and gives you a correct execution plan and advice accordingly.
Remember that execution plan does not show the plan of user defined functions called with in the query.

Subquery returns more than 1 row sql query

I had such an error can explain what I did wrong?
I only add this sql query:
(? = (select travel_region_id from relationships where travel_id = travels.id))
error
ActiveRecord::StatementInvalid (Mysql::Error: Subquery returns more than 1 row: select count(*) from travel_start_days, cars, travels
where travels.id = travel_start_days.travel_id and travels.id = travel.car_id and travel_start_days.day > adddate(curdate(), interval '2' day) and (7 = (select travel_region_id from relationships where travel_id = travels.id)) and '2013-08-16' <= travel_start_days.day):
Update Whis is method create query
def conditions
where = ''
param = []
if #region && #region != ''
where += 'travels.region_id = ?'
param += [#region.to_i]
end
if #car && #car != ''
where += ' and ' if where != ''
where += 'cars.id = ?'
param += [#car.to_i]
end
if #relation && #relation != ''
where += ' and ' if where != ''
where += '(? = (select travel_region_id from relationships where travel_id = travels.id))'
param += [#relation.to_i]
end
if #start_port && #start_port != ''
where += ' and ' if where != ''
where += '(? = (select location_id from travel_days where travel_id = travel_start_days.travel_id and day_no = 1 order by arrival asc limit 1))'
param += [#start_port.to_i]
end
return where == '' ? nil : ["travel_start_days.day > adddate(curdate(), interval ? day) and " + where] + [#criteria[5]] + param
end
The issue in this part of conditions:
(7 = (select travel_region_id from relationships where travel_id = travels.id))
Obviously this subquery returns more than one travel_region_id just replace = with IN
(7 IN (select travel_region_id from relationships where travel_id = travels.id))
If you are getting more than 1 row from subquery, then add group by clause to your subquery
SELECT travel_region_id FROM relationships
WHERE travel_id = travels.id
GROUP BY travel_region_id