Can we choose columns in the table using a CASE subquery inside the SELECT in SQL? - sql

I have one main table and two support table. I need to extract information from all three tables into one table. However, the two support table have conflicting information. Thus, in the big table, only certain rows should have the value from one of the support table while others should have the value from the other support table. I would like to choose the data inputted base on some condition using a CASE statement
This sql code is within an R language code for other purposes. But the sql code is independent and no errors are related to the R code. The A.A11 and C.C1 are all type character while A.A12 and C.C1 are all numeric.
"SELECT ",
"A.A1, A.A3,",
"CASE",
"WHEN A.A12 = 0 THEN C.C6, C.C7",
"ELSE B.B6, B.B7",
"END",
"FROM ((A",
"INNER JOIN B",
"ON A.A12 = B.B1)",
"INNER JOIN C",
"ON CAST(A.A11 AS varchar(10)) = CAST(C.C1 AS varchar(10)))"
Warning in sqlExecute(con, query, sqlParams, fetch = TRUE, stringsAsFactors = FALSE) :
42000 102 [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near ','.
Warning in sqlExecute(con, query, sqlParams, fetch = TRUE, stringsAsFactors = FALSE) :
42000 8180 [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared.
Warning: Error in sqlExecute: 42000 102 [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near ','.
42000 8180 [Microsoft][ODBC SQL Server Driver][SQL Server]Statement(s) could not be prepared.
[RODBCext] Error: SQLExecute failed

As near as I can tell, you want to do something along these lines...
SELECT
A.A1,
A.A3,
CASE WHEN A.A12 = 0 THEN C.C6 ELSE B.6 END AS X6,
CASE WHEN A.A12 = 0 THEN C.C7 ELSE B.7 END AS X7,
FROM A INNER JOIN B ON A.A12 = B.B1
INNER JOIN C ON CAST(A.A11 AS varchar(10)) = CAST(C.C1 AS varchar(10))

Related

Trying to perform an SQL join between two filtered tables

I am trying to join two tables, but with filters applied to both. eg. Have the left table filtered and then joined with a filtered version of the right table, preserving the left table.
My query is below:
SELECT REP_Exposure_secured.DeliveryRegion, REP_Exposure_secured.DeliveryCountry,
REP_Exposure_secured.EngagementCompanyCode, REP_Exposure_secured.EngagementId,
REP_Exposure_secured.Engagement, REP_Exposure_secured.EngagementType,
REP_Exposure_secured.EngagementStatus, REP_Exposure_secured.EngagementPartner,
REP_Exposure_secured.EngagementPartnerID, REP_Exposure_secured.EngagementManager,
REP_Exposure_secured.ServiceLine, REP_Exposure_secured.SubServiceLine,
REP_Exposure_secured.Competency, REP_Exposure_secured.ServiceOffering,
REP_Exposure_secured.EngagementServiceCode, REP_Exposure_secured.EngagementService,
REP_Exposure_secured.EngagementLastTimeChargedDate, REP_Exposure_secured.EngagementCreationDate,
REP_Exposure_secured.Account, REP_Exposure_secured.UltimateDunsNumber,
REP_Exposure_secured.Client, REP_Exposure_secured.ClientID,
REP_Exposure_secured.AR_0_30, REP_Exposure_secured.AR_31_60,
REP_Exposure_secured.AR_61_90, REP_Exposure_secured.AR_91_120,
REP_Exposure_secured.AR_121_150, REP_Exposure_secured.AR_151_179,
REP_Exposure_secured.AR_180_365, REP_Exposure_secured.AR_Above_365,
REP_Exposure_secured.MTD_TER, REP_Exposure_secured.MTD_BilledAmt,
REP_Exposure_secured.MTD_CollectedAmt, REP_Exposure_secured.UnbilledInvAging30Amt,
REP_Exposure_secured.UnbilledInvAging60Amt, REP_Exposure_secured.UnbilledInvAging90Amt,
REP_Exposure_secured.UnbilledInvAging150Amt, REP_Exposure_secured.UnbilledInvAging180Amt,
REP_Exposure_secured.UnbilledInvAging365Amt, REP_Exposure_secured.UnbilledInvAging365PlusAmt,
REP_FTEReport_secured.GPN, REP_FTEReport_secured.Country AS FTE_Country,
REP_FTEReport_secured.Country AS FTE_Country.EmployeeName AS FTE_Name
FROM Reporting.REP_Exposure_secured
LEFT JOIN REP_FTEReport_secured
ON REP_Exposure_secured.EngagementPartnerID = REP_FTEReport_secured.GUI
WHERE (REP_Exposure_secured.DeliveryCountry IN ('Cambodia', 'Singapore', 'Malaysia', 'Indonesia',
'Guam', 'Laos', 'Maldives', 'Myanmar', 'Philippines', 'Sri Lanka', 'Thailand', 'Vietnam')
OR REP_Exposure_secured.DeliveryCountry LIKE 'Brunei Daruss%')
AND REP_Exposure_secured.SubServiceLine='Forensics'
AND REP_Exposure_secured.EngagementType LIKE 'External%'
AND REP_Exposure_secured.Currency='USD'
AND REP_FTEReport_secured.AccountingCycleDate IN
(
SELECT
DISTINCT
MAX(AccountingCycleDate)
FROM
REP_FTEReport_secured
)
AND REP_FTEReport_secured.Country IN ('Brunei', 'Cambodia', 'Guam', 'Indonesia', 'Lao', 'Malaysia', 'Maldives',
'Myanmar', 'Philippines', 'Singapore', 'Sri Lanka', 'Thailand', 'Vietnam')
AND REP_FTEReport_secured.SubServiceLine='Forensics'
AND REP_FTEReport_secured.RankName IN ('Partner', 'Director', 'Executive Director');
This returns the following error:
: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '.'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'AND'. (156)")
Any help on what I am doing wrong would be greatly appreciated!
I think your problem is with this line, the last field in your select clause.
REP_FTEReport_secured.Country AS FTE_Country.EmployeeName AS FTE_Name
it has 2 aliases and 2 dots
The mixup is in the last 2 lines
REP_FTEReport_secured.GPN, REP_FTEReport_secured.Country AS FTE_Country,
REP_FTEReport_secured.Country AS FTE_Country.EmployeeName AS FTE_Name
Lets make them more readable first
REP_FTEReport_secured.GPN,
REP_FTEReport_secured.Country AS FTE_Country,
REP_FTEReport_secured.Country AS FTE_Country.EmployeeName AS FTE_Name
now you can see you have a problem at the end.
You probably need this
REP_FTEReport_secured.GPN,
REP_FTEReport_secured.Country AS FTE_Country,
REP_FTEReport_secured.EmployeeName AS FTE_Name
As you can see, just by making the query more readable, in this case only putting one field per line, in stead of 2, the error became visible immediate

Problematic syntax error near ")" at line 14: SQL statement - SAP Hana

I am sure that you are used to this question but nonetheless I am having trouble with my SQL script. It is very frustrating.
When I execute the SQL against the SAP Hana database, I continuously receive this error:
Errors occurred while executing the SQL statement: SAP DBTech JDBC: [257]: sql syntax error: incorrect syntax near ")": line 14 col 35
Let me present the SQL concerned here:
SELECT
BKPF.BKTXT, BKPF.MONAT, BSEG.BELNR, BSEG.BUKRS, BSEG.DMBTR, BSEG.GJAHR, BSEG.MANDT, BSEG.PRCTR, BSEG.SAKNR, CEPCT.KTEXT, CEPCT.LTEXT, SKAT.MCOD1, SKAT.TXT20, SKAT.TXT50
FROM
SAPPR1.BSEG
INNER JOIN SAPPR1.BKPF ON BSEG.GJAHR = BKPF.GJAHR
INNER JOIN SAPPR1.CEPCT ON BSEG.PRCTR = CEPCT.PRCTR
INNER JOIN (SELECT
SAKNR, TXT20, TXT50, MCOD1
FROM
SAPPR1.SKAT
WHERE
SPRAS not LIKE '%[a-z0-9 .]%' ) AS SKAT_SUB ON BSEG.SAKNR = SKAT_SUB.SAKNR
WHERE
BKPF.MONAT = (SELECT Month('?')-1)
AND (BSEG.GJAHR = (SELECT Year('?')-1 HAVING Month('?')-1 < 4) OR BSEG.GJAHR = (SELECT Year('?') HAVING Month('?')-1 > 3))
AND BSEG.MANDT = ?
;
Unlike other DBMS HANA does not support selecting records out of nothing.
A SELECT without a FROM is not valid.
In order to create a single-row set one can use the DUMMY table.
SELECT current_date FROM DUMMY;
creates the single-row set with the result of the function expression.
Having said that, for comparisons a set is not required. Instead the function can be directly put into the expression:
WHERE
BKPF.MONAT = (MONTH(?)-1)
Also note that for string typed bind variables no quotation marks are required or allowed.

[SQL Server]Incorrect syntax near the keyword 'as'

I have problem with this syntax, here is my SQL Server query.
I want to set null to functloc column based on column supereq where system status='esto'
update ih08pkgmf as t1,
(select Equipment, `System status`, `Functional loc.`
from ih08pkgmf
where `System status` = 'ESTO'
and `Superord.Equip.` is null) as t2
set t1.`System status` = t2.`System status`,
t1.`Functional loc.` = t2.`Functional loc.`
where
t1.`Superord.Equip.` = t2.Equipment`
Expected result is, all the equipment column where system='aseq' based on supereq system status='esto' the functloc is null

SQL error in DB2

I am trying to find the average number of transactions for every product key for the specified time keys. This is the query in DB2.
select
act.product_key
avg(act.cnt) as avg_transaction
from tb1 as ca
inner join tb2 as act
on ca.base_key = act.base_key and act.time = ca.time and act.product_key = ca.product_key
group by act.product_key, act.time
having act.time in (16476,16516, 16556,16596, 16636,16676,16716, 16756, 16796,16836,16876,16916,16956);
This is the error I am getting for the above query. I am not sure whats going wrong, this is the first time I am querying on DB2. Any suggestions would be great.
Error: DB2 SQL Error: SQLCODE=-104, SQLSTATE=42601, SQLERRMC=(;act.product_key
avg;,, DRIVER=3.66.46
SQLState: 42601
ErrorCode: -104
Error: DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-104;42601;(|act.product_key
avg|,, DRIVER=3.66.46
SQLState: 56098
ErrorCode: -727
The way you describe what you want, you should move the having to a where clause and remove the time key from the group by:
select act.product_key, avg(act.cnt) as avg_transaction
from tb1 ca inner join
tb2 act
on ca.base_key = act.base_key and act.time = ca.time and act.product_key = ca.product_key
where act.time in (16476, 16516, 16556,16596, 16636, 16676, 16716, 16756, 16796, 16836, 16876, 16916, 16956)
group by act.product_key;
I'm not sure if that will fix your problem.

Execute SQL-functions in R, Microsoft SQL Server

I have a number of functions written on our Microsoft SQL servers.
I can easily access and query all data normally, but I cannot execute functions on the server using RODBC.
How can I execute sql-functions using R? Are there other packages that can do this?
Or do I need to switch strategies completely?
Example:
require(RODBC)
db <- odbcConnect("db")
df <- sqlQuery(channel = db, query = "USE [Prognosis]
GO
SELECT * FROM [dbo].[Functionname] ("information_variable")
GO" )
Error message:
"42000 102 [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'GO'."
[2] "[RODBC] ERROR: Could not SQLExecDirect 'USE... "
This turned out to work:
df <- sqlQuery(channel = db,
query = "SELECT * FROM [dbo].[Functionname] ("information_variable")" )
So I dropped USE [The_SQL_TABLE] and GO