Try to use large SQL query - sql

I try to use white large SQL query like this:
insert into R7810TEST
(select 1111111 , 111111 , 1111111 ,'ORG' ,R401.ZIHUI_BAAL_POLISA ,8990 ,'ID' ,R401.ZIHUI_M_RASHI , R401.M_POLISA ,R440.M_SOCHEN , 201507 ,'ORG' , R401.ZIHUI_BAAL_POLISA ,'RTP' , 'CUR' , '1', '*' ,0 ,10000.00 ,0.00 , 0.00 , 0.00, 0.00, 0.00 , 0.00,0.00, 0.00 , r430.hf_oved_tagmulim_45 ,r430.hf_mavid_tagmulim , r430.hf_mavid_pizuim_mukar , 0.00, r430.hf_mavid_chelef, r430.hf_oved_shonot, r430.hf_mavid_shonot , r430.hf_oved_tagmulim_47 ,'MNG', 0.00 , 0.00 ,0.00 ,0.00 , '*' , to_date ('20150701', 'yyyymmdd'), R401.ZIHUI_BAAL_POLISA, r400.sug_polisa, to_date ('20150701', 'yyyymmdd'),'CHI', '12' , 0, 0 ,'0', to_date ('19000101', 'yyyymmdd')
from r400 R400 ,r401 R401 ,r430 r430 ,r440 r440
where r400.m_polisa = r401.m_polisa
and r401.m_polisa = r430.m_polisa
and r430.m_polisa= r440.m_polisa
and r401.tr_rishum in (select max(aa.tr_rishum) from r401 aa where aa.m_polisa = r401.m_polisa)
and r430.tr_rishum in (select max(aa.tr_rishum) from r430 aa where aa.m_polisa = r430.m_polisa)
and r440.tr_rishum in (select max(aa.tr_rishum) from r440 aa where aa.m_polisa = r440.m_polisa)
and r401.status_rashi = 10
--and r401.status_rashi in (30,35)
----and r401.status_rashi in (90)
--and r401.status_rashi = 20
and r400.sug_polisa in ('1','3','5','7')
and r400.sug_hishtatfut <>0
and r400.sug_hazmada <>0
and r400.m_polisa IN (XXXXX));
And I get an exception from SQL, I use Oracle and vba via Excel, I think this too large string so it's not work and the sql get part of query. What can I do with how can I use this query in vba code?

I can see some possible things at play here. It's hard to tell without the DDL for R7810TEST, but I have 2.5 guesses
The last statement in your SQL says r400.m_polisa IN (XXXXX). This does not appear to be strongly typed. Was this a placeholder, or is this the real SQL? If XXXXX is a string, you need quotes. If it's supposed to be a number, well... you know. If it's a field in one of the tables, then I suppose it's okay, but it's a weird construct if that's the case.
VBA doesn't do well with large concatenations. You didn't list your VBA code, but I can easily see it puking on a string as large as yours. To get around this, you can break the concatenation up into multiple steps. While your SQL actually appears to have balanced parentheses (with the exception of the fact that the parentheses around the select statement are unnecessary), when you are trying to wrap this in VBA strings, it's not difficult to miss something small.
A follow-up on item 2 -- again with VBA concatenation, something as simple as a missing space can derail your best SQL. For example:
For example:
sql = "select one, two, three" & _
"from foo"
Unintentionally becomes:
select one, two, threefrom foo
Sample for point #2:
cmd.CommandText = _
"insert into R7810TEST" & _
"select" & _
" 1111111 , 111111 , 1111111 ,'ORG' ,R401.ZIHUI_BAAL_POLISA ,8990 ,'ID' ," & _
" R401.ZIHUI_M_RASHI , R401.M_POLISA ,R440.M_SOCHEN , 201507 ,'ORG' ," & _
" R401.ZIHUI_BAAL_POLISA ,'RTP' , 'CUR' , '1', '*' ,0 ,10000.00 ," & _
" 0.00 , 0.00 , 0.00, 0.00, 0.00 , 0.00,0.00, 0.00 ," & _
" r430.hf_oved_tagmulim_45 ,r430.hf_mavid_tagmulim ," & _
" r430.hf_mavid_pizuim_mukar , 0.00, r430.hf_mavid_chelef," & _
" r430.hf_oved_shonot, r430.hf_mavid_shonot , r430.hf_oved_tagmulim_47 ," & _
" 'MNG', 0.00 , 0.00 ,0.00 ,0.00 , '*' , to_date ('20150701', 'yyyymmdd')," & _
" R401.ZIHUI_BAAL_POLISA, r400.sug_polisa, to_date ('20150701', 'yyyymmdd')," & _
" 'CHI', '12' , 0, 0 ,'0', to_date ('19000101', 'yyyymmdd') "
cmd.CommandText = cmd.CommandText & _
"from r400 R400 ,r401 R401 ,r430 r430 ,r440 r440 " & _
"where r400.m_polisa = r401.m_polisa " & _
"and r401.m_polisa = r430.m_polisa " & _
"and r430.m_polisa= r440.m_polisa " & _
"and r401.tr_rishum in (select max(aa.tr_rishum) " & _
"from r401 aa where aa.m_polisa = r401.m_polisa) " & _
"and r430.tr_rishum in (select max(aa.tr_rishum) " & _
"from r430 aa where aa.m_polisa = r430.m_polisa) " & _
"and r440.tr_rishum in (select max(aa.tr_rishum) " & _
"from r440 aa where aa.m_polisa = r440.m_polisa) " & _
"and r401.status_rashi = 10 " & _
"and r400.sug_polisa in ('1','3','5','7') " & _
"and r400.sug_hishtatfut <>0 " & _
"and r400.sug_hazmada <>0 " & _
"and r400.m_polisa IN ('XXXXX')"
When in doubt, make liberal use of whitespace in your SQL.
Parting shot -- if this doesn't help, please post the DDL for your tables. It may provide a hint as to what's wrong.

You don't say what the error is, but it looks like your insert...select is malformed. As a matter of good practice, you should specify the columns you are inserting into before your select clause, and remove the parentheses around the select. Something like this:
insert into R7810TEST
( column1, column2, ...etc)
select 1111111 , 111111 , 1111111 ,'ORG' ...etc

Related

Update query, nested iif SET and joined tables

Trying to make an Update Query with inner join and have the SET reflect the current month number.
Need help with syntax on updating a joined table that has columns for months, need to update the months that are Month(DATE()) +1,+2 only. Trying to use the below nested IIF as "IIF(Month(Date()) ="1",( SET table.c = table2.c2......) complete code below.
Syntax error is the result
Sample data
to update sql table
linked excel with values to use for updates
Update dbo_MasterSalesForecast_Test
INNER JOIN MasterSalesForecastUpdate
ON (dbo_MasterSalesForecast_Test.SubTo=MasterSalesForecastUpdate.Item) AND( dbo_MasterSalesForecast_Test.Planner=MasterSalesForecastUpdate.Planner)
IIF(Month(Date()) ="1",( SET
dbo_MasterSalesForecast_Test.[YY:1] = [MasterSalesForecastUpdate].[YYJan],
dbo_MasterSalesForecast_Test.[YY:2] = [MasterSalesForecastUpdate].[YYFan],
dbo_MasterSalesForecast_Test.[YY:3] = [MasterSalesForecastUpdate].[YYMar])
,
IIF(Month(Date())="2",( SET
dbo_MasterSalesForecast_Test.[YY:2]=[MasterSalesForecastUpdate].[YYFeb],
dbo_MasterSalesForecast_Test.[YY:3]=[MasterSalesForecastUpdate].[YYMar],
dbo_MasterSalesForecast_Test.[YY:4]=[MasterSalesForecastUpdate].[YYApr])
,
IIF(Month(Date())="3",( SET
dbo_MasterSalesForecast_Test.[YY:3]=[MasterSalesForecastUpdate].[YYMar],
dbo_MasterSalesForecast_Test.[YY:4]=[MasterSalesForecastUpdate].[YYApr],
dbo_MasterSalesForecast_Test.[YY:5]=[MasterSalesForecastUpdate].[YYMay])
,
IIF(Month(Date())="4",(SET
dbo_MasterSalesForecast_Test.[YY:4]=[MasterSalesForecastUpdate].[YYApr],
dbo_MasterSalesForecast_Test.[YY:5]=[MasterSalesForecastUpdate].[YYMay],
dbo_MasterSalesForecast_Test.[YY:6]=[MasterSalesForecastUpdate].[YYJun])
,
IIF(Month(Date())="5",(SET
dbo_MasterSalesForecast_Test.[YY:5]=[MasterSalesForecastUpdate].[YYMay],
dbo_MasterSalesForecast_Test.[YY:6]=[MasterSalesForecastUpdate].[YYJun],
dbo_MasterSalesForecast_Test.[YY:7]=[MasterSalesForecastUpdate].[YYJul])
,
IIF(Month(Date())="6",(SET
dbo_MasterSalesForecast_Test.[YY:6]=[MasterSalesForecastUpdate].[YYJun],
dbo_MasterSalesForecast_Test.[YY:7]=[MasterSalesForecastUpdate].[YYJul],
dbo_MasterSalesForecast_Test.[YY:8]=[MasterSalesForecastUpdate].[YYAug])
,
IIF(Month(Date())="7",(SET
dbo_MasterSalesForecast_Test.[YY:7]=[MasterSalesForecastUpdate].[YYJul],
dbo_MasterSalesForecast_Test.[YY:8]=[MasterSalesForecastUpdate].[YYAug],
dbo_MasterSalesForecast_Test.[YY:9]=[MasterSalesForecastUpdate].[YYSep])
,
IIF(Month(Date())="8",(SET
dbo_MasterSalesForecast_Test.[YY:8]=[MasterSalesForecastUpdate].[YYAug],
dbo_MasterSalesForecast_Test.[YY:9]=[MasterSalesForecastUpdate].[YYSep],
dbo_MasterSalesForecast_Test.[YY:10]=[MasterSalesForecastUpdate].[YYOct])
,
IIF(Month(Date())="9",(SET
dbo_MasterSalesForecast_Test.[YY:9]=[MasterSalesForecastUpdate].[YYSep],
dbo_MasterSalesForecast_Test.[YY:10]=[MasterSalesForecastUpdate].[YYOct],
dbo_MasterSalesForecast_Test.[YY:11]=[MasterSalesForecastUpdate].[YYNov])
,
IIF(Month(Date())="10",(SET
dbo_MasterSalesForecast_Test.[YY:10]=[MasterSalesForecastUpdate].[YYOct],
dbo_MasterSalesForecast_Test.[YY:11]=[MasterSalesForecastUpdate].[YYNov],
dbo_MasterSalesForecast_Test.[YY:12]=[MasterSalesForecastUpdate].[YYDec])
,
IIF(Month(Date())="11",(SET
dbo_MasterSalesForecast_Test.[YY:11]=[MasterSalesForecastUpdate].[YYNov],
dbo_MasterSalesForecast_Test.[YY:12]=[MasterSalesForecastUpdate].[YYDec],
dbo_MasterSalesForecast_Test.[YY+1:1]=[MasterSalesForecastUpdate].[YY+1Jan])
,
IIF(Month(Date())="12"(SET
dbo_MasterSalesForecast_Test.[YY:12]=[MasterSalesForecastUpdate].[YYDec],
dbo_MasterSalesForecast_Test.[YY+1:1]=[MasterSalesForecastUpdate].[YY+1Jan],
dbo_MasterSalesForecast_Test.[YY+1:02]=[MasterSalesForecastUpdate].[YY+1Feb])
)))))))))));
Cannot conditionally reference fields. Field must be static in query object then value to update with can be determined in an IIf() for each field. Use VBA to build and execute action SQL statement.
CurrentDb.Execute "UPDATE dbo_MasterSalesForecast_Test " & _
"INNER JOIN MasterSalesForecastUpdate " & _
"ON (dbo_MasterSalesForecast_Test.SubTo=MasterSalesForecastUpdate.Item) " & _
"AND (dbo_MasterSalesForecast_Test.Planner=MasterSalesForecastUpdate.Planner) " & _
"SET [YY:" & Month(Date()) & "] = [YY" & Format(Date(),"mmm") & "]," & _
"[YY:" & Month(DateAdd("m",1,Date())) & "] = [YY" & Format(DateAdd("m",1,Date()),"mmm") & "]," & _
"[YY:" & Month(DateAdd("m",2,Date())) & "] = [YY" & Format(DateAdd("m",2,Date()),"mmm") & "]"

MS ACCESS SQL Join Subquery

I have two tables: newparts, storedparts
I insert the parts of the newparts, which are not jet in the storedparts into the storedparts:
SQL_String = "INSERT INTO storedparts " & _
"SELECT newparts.* " & _
"FROM storedparts " & _
"RIGHT JOIN newparts ON (storedparts.identifier = newparts.identifier) AND (storedparts.timeStamp = newparts.timeStamp) " & _
"WHERE ((storedparts.AutoID) Is Null);"
This is working fine so far. Now the Problem: Table storedparts is getting so big that the programm is taking too Long for the join process. My solution: Just compare the newparts not to all parts of the storedparts, but just to parts that aren't older than 4 days... I tried a subquery like this, but i can't get it to run.
SQL_String = "INSERT INTO storedparts " & _
"SELECT newparts.* " & _
"FROM storedparts (WHERE storedparts.timestamp > Now() - 4) " & _
"RIGHT JOIN newparts ON (storedparts.identifier = newparts.identifier) AND (storedparts.timeStamp = newparts.timeStamp) " & _
"WHERE ((storedparts.AutoID) Is Null);"
Any help is appreciated.
This wouldn't be a problem if your tables have indexes.
CREATE INDEX ndx_sp_identifier ON storedparts (identifier);
CREATE INDEX ndx_np_identifier ON newparts (identifier);
Then I suggest you change your query to something like this as #jarlh pointed out.
INSERT INTO storedparts
SELECT newparts.*
FROM newparts
LEFT JOIN storedparts
ON newparts.identifier = storedparts.identifier
AND newparts.timeStamp = storedparts.timeStamp
WHERE storedparts.AutoID Is Null;
You could add the where clause after the join statements and see if it improves the performance of the query . Else Try this and see if it works
SQL_String = "INSERT INTO storedparts " & _
"SELECT newparts.* " & _
"FROM ( SELECT * FROM storedparts WHERE
storedparts.timestamp > DateAdd ( 'd', -4, Now()) )sparts" & _
"RIGHT JOIN newparts ON (sparts.identifier = newparts.identifier) AND
(sparts.timeStamp = newparts.timeStamp) " & _
"WHERE ((sparts.AutoID) Is Null);"

SQL SERVER 2008 select statement with case

I have a Select statement in my VB6 application....
Here's what it looks like.....
Dim str As string
str = "SELECT CompID, Department from tblCompanies " & _
"Where CompID in (123, 234, 345, 456) " & _
"Order by CompID "
So what I'm tryign to do here is add a CASE WHEN statement to WHERE clause - basically I'm looking to add a string to each Department name, depending on the COMPID. So I need to specify that these are the COMPID's that I want to select, then I want to do soemthing like
Case when CompID = 123 Then ----ADD "GC" to that Department Name
I guess I need to do this before I open my recordset with
rs.open str, g_CN, adOpenStatic
Because once it's open it seems to be giving me errors when I try to edit it.
All in all, if my recordset looks like this...
Accounting
Finance
IT
R&D
I'm trying to make it look like
"GC" - Accounting
"GC" - Finance
"BP" - IT
"DC" - R&D
change it to,
Dim str As string
str = "SELECT CompID, CASE WHEN CompID IN (123,234) THEN 'GC' " & _
" WHEN CompID = 345 THEN 'IT' " & _
" WHEN CompID = 456 THEN 'DC' " & _
" ELSE '' END + ' - ' + Department AS Department from tblCompanies " & _
"Where CompID in (123, 234, 345, 456) " & _
"Order by CompID "
Try this:
str = "SELECT CompID, CASE WHEN CompID = 123 THEN '""GC"" - ' ELSE '' END + Department As Department from tblCompanies " & _
"Where CompID in (123, 234, 345, 456) " & _
"Order by CompID "

Query syntax on a large inner-joined select query linked to a control giving runtime 3071 error message

I am getting Runtime error message 3071 on the following query stating that the query is too complex. I have created queries in the past which have seemed more complex than this one. I would like to understand what generates this message:
sql_get = "SELECT tblValueChain01.IDMacroProcesso, tblValueChain02.IDMicroProcesso02, tblValueChain03.ID, tblDependencies01.ID AS DependencyID, tblValueChain02.MicroProcesso02, tblValueChain01.MacroProcess, tblValueChain01.TeamLead, tblValueChain01.LastOrganisationDate, tblValueChain01.TempiIndeterminati, tblValueChain01.TempiDeterminati, tblValueChain01.Interinali, tblValueChain01.PartTime, tblValueChain01.DailyMinutesAverage AS Minutes01, tblValueChain01.DailyMinutesHigh AS Minutes01H, tblValueChain01.DailyMinutesLow AS Minutes01L, tblValueChain02.MicroProcesso02, " & _
"tblValueChain02.DailyMinutesAverage AS Minutes02, tblValueChain02.DailyMinutesHigh AS Minutes02H, tblValueChain02.DailyMinutesLow AS Minutes02L, tblValueChain03.MicroProcess, tblValueChain03.MinutesPerDay AS Minutes03, tblValueChain03.MinutesPerDayHigh AS Minutes03H, tblValueChain03.MinutesPerDayLow AS Minutes03L, tblDependencies01.FlowDescription, tblDependencies01.FlowType, tblTeamsDepartments.Department, tblTeams.Team, tblDependencies01.Precision, " & _
"tblDependencies01.ServiceDelivery , tblDependencies01.RiskReduction, tblDependencies01.CapacityCreation, tblDependencies01.TargetCapacityCreation, tblDependencies01.Feasibility, tblDependencies01.Timeframe, tblDependencies01.Priority, tblDependencies01.Note, tblDependencies01.RedundantControls, tblDependencies01.RedundantControlsNotes, tblDependencies01.RedundantControlsPotSolution, tblDependencies01.RedundantControlsNotesSymbol, tblDependencies01.RedundantControlsPotSolSymbol, tblDependencies01.RolesAndResponsibilities, tblDependencies01.RolesAndResponsibilitiesNotes, " & _
"tblDependencies01.RolesAndResponsibilitiesPotSolution , tblDependencies01.RolesResponNotesSymbol, tblDependencies01.RolesRespPotSolSymbol, tblDependencies01.SubstandardSvcs, tblDependencies01.SubstandardSvcsNotes, tblDependencies01.SubStandardSvcsPotSolution, tblDependencies01.SubStandardSvcsNotesSymbol, tblDependencies01.SubStandardSvcsPotSolSymbol, tblDependencies01.KnowledgeGaps, tblDependencies01.KnowledgeGapsNotes, tblDependencies01.KnowledgeGap, " & _
"PotSolution , tblDependencies01.KnowledgeGapsNotesSymbol, tblDependencies01.KnowledgeGapsPotSolSymbol, tblDependencies01.ExcessiveOversight, tblDependencies01.ExcessiveOversightNotes, tblDependencies01.ExcessiveOversightPotSolution, tblDependencies01.ExcessiveOversightNotesSymbol, tblDependencies01.ExcessiveOversightPotSolSymbol, tblDependencies01.UpstreamErrors, tblDependencies01.UpstreamErrorsNotes, tblDependencies01.UpstreamErrorsPotSolution, tblDependencies01.UpstreamErrorsNotesSymbol, tblDependencies01.UpstreamErrorsPotSolSymbol, tblDependencies01.DefectsRework, " & _
"tblDependencies01.DefectsReworkNotes , tblDependencies01.DefectsReworkPotSolution, tblDependencies01.DefectsReworkNotesSymbol, tblDependencies01.DefectsReworkPotSolSymbol, tblDependencies01.OverProduction, tblDependencies01.OverproductionNotes, tblDependencies01.OverproductionPotSolution, tblDependencies01.OverproductionNotesSymbol, tblDependencies01.OverproductionPotSolSymbol, tblDependencies01.MotionTransport, " & _
"tblDependencies01.MotionTransportNotes , tblDependencies01.MotionTransportPotSolution, tblDependencies01.MotionNotesSymbol, tblDependencies01.MotionSolSymbol, tblDependencies01.DowntimeWaiting, tblDependencies01.DowntimeWaitingNotes, tblDependencies01.DowntimeWaitingPotSolution, tblDependencies01.WaitDowntimeNotesSymbol, tblDependencies01.WaitDowntimeSolSymbol, tblDependencies01.ExcessiveHandoffs, tblDependencies01.ExcessiveHandoffNotes, tblDependencies01.ExcessiveHandoffPotSolution, " & _
"tblDependencies01.ExcessiveHandoffsSymbol , tblDependencies01.ExcessiveHandoffsPotSolSymbol, tblDependencies01.RCSLABreachInternal, tblDependencies01.RCSLABreachExternal, tblDependencies01.RCCorporatePolicyBreach, tblDependencies01.RCOperatingModelDiscrepancy, tblDependencies01.RRSLABreachInternal, tblDependencies01.RRSLABreachExternal, tblDependencies01.RRCorporatePolicyBreach, tblDependencies01.RROperatingModelDiscrepancy, tblDependencies01.SSSLABreachInternal, tblDependencies01.SSSLABreachExternal, tblDependencies01.SSCorporatePolicyBreach, " & _
"tblDependencies01.SSOperatingModelDiscrepancy , tblDependencies01.KGSLABreachInternal, tblDependencies01.KGSLABreachExternal, tblDependencies01.KGCorporatePolicyBreach, tblDependencies01.KGOperatingModelDiscrepancy, tblDependencies01.EOSLABreachInternal, tblDependencies01.EOSLABreachExternal, tblDependencies01.EOCorporatePolicyBreach, tblDependencies01.EOOperatingModelDiscrepancy, tblDependencies01.UESLABreachInternal, tblDependencies01.UESLABreachExternal, tblDependencies01.UECorporatePolicyBreach, tblDependencies01.UEOperatingModelDiscrepancy, tblDependencies01.DefSLABreachInternal, " & _
"tblDependencies01.DefSLABreachExternal , tblDependencies01.DefCorporatePolicyBreach, tblDependencies01.DefOperatingModelDiscrepancy, tblDependencies01.OPSLABreachInternal, tblDependencies01.OPSLABreachExternal, tblDependencies01.OPCorporatePolicyBreach, tblDependencies01.OPOperatingModelDiscrepancy, tblDependencies01.EHSLABreachInternal, tblDependencies01.EHSLABreachExternal, tblDependencies01.EHCorporatePolicyBreach, " & _
"tblDependencies01.EHOperatingModelDiscrepancy , tblDependencies01.DTSLABreachInternal, tblDependencies01.DTSLABreachExternal, tblDependencies01.DTCorporatePolicyBreach, tblDependencies01.DTOperatingModelDiscrepancy, tblDependencies01.ECSLABreachInternal, tblDependencies01.ECSLABreachExternal, tblDependencies01.ECCorporatePolicyBreach, tblDependencies01.ECOperatingModelDiscrepancy " & _
"FROM (tblTeamsDepartments INNER JOIN tblTeams ON tblTeamsDepartments.ID = tblTeams.Department) INNER JOIN (tblValueChain01 INNER JOIN ((tblValueChain03 INNER JOIN tblValueChain02 ON tblValueChain03.IDMacroProcess = tblValueChain02.IDMicroProcesso02) INNER JOIN tblDependencies01 ON tblValueChain03.ID = tblDependencies01.IDSubProcess) ON tblValueChain01.IDMacroProcesso = tblValueChain02.IDMacroProcesso01) ON tblTeams.ID = tblDependencies01.Group WHERE [tblDependencies01].[ID]= '" & ID & "'"
Form_frmValueChainDynamic01.Form.RecordSource = sql_get
Possible typo:
...
INNER JOIN tblValueChain02 ON tblValueChain03.IDMacroProcess = tblValueChain02.IDMicroProcesso02)`
...
...perhaps should be IDMacroProcesso (missing "o" at the end of this field)?
Is [tblDependencies01].[ID] a number field? If so, then in your WHERE clause you've used single quotes denoting you're expecting to match a string; so this:
WHERE [tblDependencies01].[ID]= '" & ID & "'"
...should be written like this, if ID is a number:
WHERE [tblDependencies01].[ID]=" & ID
You've referred to most fields in your SELECT clause using the tableName.fieldName convention except for PotSolution (this may not be an issue, but it's good to be consistent!)
Some more things to try if the above doesn't work: http://allenbrowne.com/subquery-02.html#QueryTooComplex

SQL decode on column4 but only when column5 is distinct

I need to change the sum(decode()) expressions that are like
SUM(Decode(vcon.WAGON_TYPE_CODE,'MS',1,0))
to something that counts rows with vcon.WAGON-TYPE-CODE = 'MS' but only when wag.ACI-TAG-NO is distinct.
So if two columns look like this
vcon.WAGON_TYPE_CODE wag.ACI_TAG_NO
MS HI1111
SS C99999
MS HI1111
MS HI7777
SS HI8888
MS HI6666
The expression needs to return the number 3 rather than 4 as SUM(Decode(vcon.WAGON_TYPE_CODE,'MS',1,0)) currently does.
Any suggestions?
querySELECT = "SELECT "
querySELECT = querySELECT & "trn.WID_DATE, "
querySELECT = querySELECT & "trn.MINE_CODE, "
querySELECT = querySELECT & "trn.TRAIN_CONTROL_ID, "
querySELECT = querySELECT & "trn.NUM_CARS as HBD_Car_Count, "
querySELECT = querySELECT & "SUM(Decode(vcon.WAGON_TYPE_CODE,'MS',1,0)) M_Series, "
querySELECT = querySELECT & "(SUM(Decode(vcon.WAGON_TYPE_CODE,'SS',1,0))-SUM(Decode(wag.ACI_TAG_NO,'HI0000',1,0))) S_Series, "
querySELECT = querySELECT & "SUM(Decode(vcon.WAGON_TYPE_CODE,'CS',1,0)) C_Series, "
querySELECT = querySELECT & "SUM(Decode(wag.ACI_TAG_NO,'HI0000',1,0)) as No_Tag, "
querySELECT = querySELECT & "(COUNT(1) - trn.NUM_CARS) DB_Mismatch "
queryFROM = "FROM widsys.consist con, widsys.train trn, widsys.wagon wag, widsys.v_consist_ore_detail vcon "
queryWHERE = "WHERE trn.TRAIN_RECORD_ID = con.TRAIN_RECORD_ID "
queryWHERE = queryWHERE & "AND con.WAGON_ID = wag.WAGON_ID "
queryWHERE = queryWHERE & "AND ((vcon.CONSIST_ID=con.CONSIST_ID) "
queryWHERE = queryWHERE & "AND trn.MINE_CODE In (" & mine & ") "
queryWHERE = queryWHERE & "AND (trn.DIRECTION='N') "
queryWHERE = queryWHERE & "AND (wag.ACI_TAG_TYPE In ('CONTROL','SLAVE','ORE')) "
queryWHERE = queryWHERE & "AND (trn.WID_DATE>={ts '" & startDate & "'} "
queryWHERE = queryWHERE & "AND trn.WID_DATE<={ts '" & endDate & "'})) "
queryGROUPBY = "GROUP BY trn.WID_DATE, trn.MINE_CODE, trn.TRAIN_CONTROL_ID, trn.NUM_CARS "
queryORDERBY = "ORDER BY trn.WID_DATE DESC"
I think the following should work (this count the distinct wag.ACI_TAG_NO only when vcon.WAGON_TYPE_CODE='MS') :
COUNT(DISTINCT Decode(vcon.WAGON_TYPE_CODE,'MS',wag.ACI_TAG_NO,NULL))
e-g:
SQL> WITH data AS (
2 SELECT 'MS' WAGON_TYPE_CODE, 'HI1111' ACI_TAG_NO FROM DUAL UNION ALL
3 SELECT 'SS', 'C99999' FROM DUAL UNION ALL
4 SELECT 'MS', 'HI1111' FROM DUAL UNION ALL
5 SELECT 'MS', 'HI7777' FROM DUAL UNION ALL
6 SELECT 'SS', 'HI8888' FROM DUAL UNION ALL
7 SELECT 'MS', 'HI6666' FROM DUAL
8 )
9 SELECT COUNT(DISTINCT decode(WAGON_TYPE_CODE,'MS',ACI_TAG_NO,NULL))
10 FROM DATA
11 ;
COUNT(DISTINCTDECODE(WAGON_TYP
------------------------------
3
Cheers,
--
Vincent
You could use a subquery that filters duplicate tags. Your query is pretty complex, but this would calculate just the sum you're looking for:
SELECT SUM(Decode(sub.WAGON_TYPE_CODE,'MS',1,0))
FROM (
SELECT DISTINCT vcon.WAGON_TYPE_CODE, wag.ACI_TAG_NO
FROM widsys.wagon wag
INNER JOIN widsys.consist con
ON con.wagon_id = wag.wagon_id
INNER JOIN widsys.v_consist_ore_detail vcon
ON vcon.CONSIST_ID = con.CONSIST_ID
) sub
The DISTINCT makes sure there is only one row per (wagon_type,aci_tag_no) combination.