How to replace a subselect with a join in a case statement in SQL? - sql

I have a SQL query with a case statement. The case statement has a subquery. I want to replace (delete) the subselect with a join. It is possible? How can i do it?
The Query:
SELECT tablex.Abnumber, CASE WHEN Abdate is not null AND isnull(Abnumber,0) > 1 AND Abdate < (SELECT Abdate FROM t_tablex WHERE Annumber = #Annumber AND Abnumber= #Abnumber-1) THEN 'bla bla' ELSE '' END
FROM t_tablex AS tablex
WHERE (#Annumber IS NULL OR tablex.Annumber= #Annumber)
AND (#AbnumberIS NULL OR tablex.Abnumber= #Abnumber)

SELECT tablex.Abnumber,
CASE WHEN isnull(Abnumber,0) > 1 AND Abdate < a.Abdate THEN 'bla bla' ELSE '' END
FROM t_tablex AS tablex
LEFT JOIN (SELECT Abdate
FROM t_tablex
WHERE Annumber = #Annumber AND Abnumber= #Abnumber-1
) A ON A.Annumber = tablex.Annumber AND a.Abnumber = tablex.Abnumber
WHERE tablex.Annumber= #Annumber
AND tablex.Abnumber= #Abnumber

I suspect that LAG() does what you want:
SELECT x.Abnumber,
(CASE WHEN x.Abdate is not null AND
x.Abnumber > 1 AND
x.Abdate < prev_Abdate
THEN 'bla bla'
ELSE ''
END)
FROM (SELECT x.*,
LAG(Abdate) OVER (PARTITION BY Annumber ORDER BY Abnumber) as prev_Abdate)
FROM t_tablex x
) x
WHERE (#Annumber IS NULL OR x.Annumber= #Annumber) AND
(#Abnumber IS NULL OR x.Abnumber = #Abnumber);
This is not exactly equivalent to your query, unless some assumptions are made about the data. However, I suspect it is actually what you intend.

Thanks for the answers. I tried some things and found the following solutions:
Solution 1 (replace subselect with inner join):
SELECT tablex.Abnumber,
CASE WHEN tablex.Abdate is not null
AND isnull(tablex.Abnumber,0) > 1
AND tablex.Abdate < tablex2.Abdate
THEN 'bla bla'
ELSE '' END
FROM t_tablex AS tablex
INNER JOIN t_tablex as tablex2
ON tablex.Annumber = tablex2.Annumber
AND tablex.Abnumber = tablex2.Abnumber + 1
WHERE tablex.Annumber = ISNULL( #Annumber, tablex.Annumber)
AND tablex.Abnumber = ISNULL( #Abnumber, tablex.Abnumber)
Solution 2 (with LAG()):
SELECT base.*
FROM (
SELECT tablex.Abnumber,
CASE WHEN tablex.Abdate is not null
AND tablex.Abnumber > 1
AND tablex.Abdate < LAG( tablex.Abdate, 1 ) OVER ( PARTITION BY tablex.Annumber ORDER BY tablex.Abnumber)
THEN 'bla bla'
ELSE '' END AS ERG
FROM t_tablex AS tablex
WHERE tablex.Annumber = ISNULL( #Annumber, tablex.Annumber )
AND tablex.Abnumber BETWEEN ISNULL( #Abnumber , tablex.Abnumber) - 1
AND ISNULL( #Abnumber, tablex.Abnumber )
) base
WHERE
base.Abnumber = ISNULL( #Abnumber, base.Abnumber )

Related

Postgres: missing FROM-clause entry for table - SQL

good afternoon I have a query that I am not able to show the column of the table (dpa.view_workflowjob_client) column (f_name), when I place (c.f_name) do not select to view the error (missing entry from the FROM clause for the table). see below:
select
wfjc.f_agent_name,
wfjc.f_policy_name,
wfjc.f_workflow_name,
wfjc.f_workflow_jobid,
wfjc.f_status,
wfjc.f_completion_status,
wfjc.f_completion_report,
wfjc.f_starttime,
wfjc.f_endtime,
wfjc.f_missed_clients,
wfjc.f_disabled_clients,
c.f_name
from (
select *
from dpa.view_workflowjob wfj
left join
(
select
c.f_workflowjob_id,
case when count(c.dis) > 0
then count(c.dis)
else null
end f_disabled_clients,
case when count(c.msd) > 0
then count(c.msd)
else null
end f_missed_clients
from
(
select
f_name,
f_workflowjob_id,
case when f_status = 'disabled'
then 1
else null
end dis,
case when f_status = 'missed'
then 1
else null
end msd
from dpa.view_workflowjob_client
where f_starttime <= 1606146420 AND f_endtime >= 1605023220
) c
group by c.f_workflowjob_id
) clients
on clients.f_workflowjob_id = wfj.f_id
) wfjc
where (
(wfjc.f_starttime <= 1606146420 AND wfjc.f_endtime >= 1605023220 AND ( (wfjc.f_agent_id = '8512813a-5654-4b18-99cc-0e812076e719') ))
)

How to return 'blank' using Sum function in Sql, if Sum is resulting 0 in SQL

I am using Sql Server 2008. I am adding some column value using Sum function. Like the code below:
SELECT 'RCOAuthorizer LMS',
'' AS Consumer_Loan,
'' AS Auto_Loan,
'' AS Credit_Card,
SUM(CASE
WHEN sq2.loan_type = 'Loan Amendment' THEN sq2.user_count
ELSE ''
END ) AS Loan_Amendment,
SUM(CASE
WHEN sq2.loan_type = 'Pre-Payment' THEN sq2.user_count
ELSE ''
END ) AS Pre_Payment,
SUM(CASE
WHEN sq2.loan_type = 'Corporate Credit card' THEN sq2.user_count
ELSE ''
END ) AS Corporate_Credit_card,
'' AS Auto_Payment_Release,
'' AS Car_Mulkiya
FROM
( SELECT 'RCOAuthorizer' AS ws_name,
'Loan Amendment' AS loan_type,
COUNT (DISTINCT a.bpm_referenceno) AS user_count,
a.user_id AS user_id
FROM BM_LMS_DecisionHistoryGrid a
INNER JOIN
( SELECT m.bpm_referenceno
FROM BM_LMS_EXTTABLE m
WHERE m.request_type = 'Loan Amendment' ) sq1 ON a.bpm_referenceno = sq1.bpm_referenceno
WHERE workstep_name = 'RCOAuthorizer'
GROUP BY a.user_id
UNION SELECT 'RCOAuthorizer',
'Pre-Payment',
COUNT (DISTINCT a.bpm_referenceno), a.user_id
FROM BM_LMS_DecisionHistoryGrid a
INNER JOIN
( SELECT m.bpm_referenceno
FROM BM_LMS_EXTTABLE m
WHERE m.request_type = 'Pre-Payment' ) sq1 ON a.bpm_referenceno = sq1.bpm_referenceno
WHERE workstep_name = 'RCOAuthorizer'
GROUP BY a.user_id
UNION SELECT 'RCOAuthorizer',
'Corporate Credit card',
COUNT (DISTINCT a.bpm_referenceno), a.user_id
FROM BM_LMS_DecisionHistoryGrid a
INNER JOIN
( SELECT m.bpm_referenceno
FROM BM_LMS_EXTTABLE m
WHERE m.request_type = 'Corporate Credit card' ) sq1 ON a.bpm_referenceno = sq1.bpm_referenceno
WHERE workstep_name = 'RCOAuthorizer'
GROUP BY a.user_id ) sq2
GROUP BY sq2.ws_name
The above query will return Sum of all the numbers available in 'a' column. But in case, there is no record, then it will return '0' as result.
I require that if there is no record, it must show blank instead of showing '0'. How to handle the same.
To start, you don't need an ISNULL with a back value of 0 (the neutral for adding) inside a SUM aggregate, as the SUM already ignores NULL values. So SUM(ISNULL(Column, 0)) is equal to SUM(Column) (but different from ISNULL(SUM(Column), 0)!).
Seems that you want a VARCHAR result instead of a numeric one. You can solve this with a CASE.
Select
CASE WHEN Sum(a) = 0 THEN '' ELSE CONVERT(VARCHAR(100), Sum(a)) END
from
table;
If you don't want to repeat the SUM expression:
;WITH SumResult AS
(
Select CONVERT(VARCHAR(100), Sum(a)) AS SumTotal
from table
)
SELECT
CASE WHEN R.SumTotal = '0' THEN '' ELSE R.SumTotal END
FROM
SumResult AS R
Keep in mind that in these both cases, if there is no record to calculate the sum from, the result will be NULL.
EDIT: There is no point in adding '' inside your SUM, as it's converted to 0 to be able to sum. The solution is still the same as I posted before.
Change
SUM(CASE
WHEN sq2.loan_type = 'Pre-Payment' THEN sq2.user_count
ELSE ''
END ) AS Pre_Payment,
for
CASE
WHEN SUM(CASE WHEN sq2.loan_type = 'Pre-Payment' THEN sq2.user_count END) = 0 THEN ''
ELSE CONVERT(VARCHAR(100), SUM(CASE WHEN sq2.loan_type = 'Pre-Payment' THEN sq2.user_count)) END AS Pre_Payment,
Just try this ( use isnull again ):
Select isnull(Sum(isnull(a,0)),0) from table_;
I used table_ instead of table, because table is a reserved keyword.
SQL Fiddle Demo

Sql server aggregate function and GROUP BY Clause error

I have a query below where it compares the number of stagingCabincrew and StagingCockpitCrew columns from the staging schema and compares them to their data schema equivalent 'DataCabinCrew' and 'DataCockpitCrew'.
Below is the query and the results outputted:
WITH CTE AS
(SELECT cd.*,
c.*,
DataFlight,
l.ScheduledDepartureDate,
l.ScheduledDepartureAirport
FROM
(SELECT *,
ROW_NUMBER() OVER(PARTITION BY LegKey
ORDER BY UpdateID DESC) AS RowNumber
FROM Data.Crew) c
INNER JOIN Data.CrewDetail cd ON c.UpdateID = cd.CrewUpdateID
AND cd.IsPassive = 1
AND RowNumber = 1
INNER JOIN
(SELECT *,
Carrier + CAST(FlightNumber AS VARCHAR) + Suffix AS DataFlight
FROM Data.Leg) l ON c.LegKey = l.LegKey )
SELECT StagingFlight,
sac.DepartureDate,
sac.DepartureAirport,
cte.DataFlight,
cte.ScheduledDepartureDate,
cte.ScheduledDepartureAirport,
SUM(CASE
WHEN sac.CREWTYPE = 'F' THEN 1
ELSE 0
END) AS StagingCabinCrew,
SUM(CASE
WHEN sac.CREWTYPE = 'C' THEN 1
ELSE 0
END) AS StagingCockpitCrew,
SUM(CASE
WHEN cte.CrewType = 'F' THEN 1
ELSE 0
END) AS DataCabinCrew,
SUM(CASE
WHEN cte.CrewType = 'C' THEN 1
ELSE 0
END) AS DataCockpitCrew
FROM
(SELECT *,
Airline + CAST(FlightNumber AS VARCHAR) + Suffix AS StagingFlight,
ROW_NUMBER() OVER(PARTITION BY Airline + CAST(FlightNumber AS VARCHAR) + Suffix
ORDER BY UpdateId DESC) AS StageRowNumber
FROM Staging.SabreAssignedCrew) sac
LEFT JOIN CTE cte ON StagingFlight = DataFlight
AND sac.DepartureDate = cte.ScheduledDepartureDate
AND sac.DepartureAirport = cte.ScheduledDepartureAirport
AND sac.CREWTYPE = cte.CrewType
WHERE MONTH(sac.DepartureDate) + YEAR(sac.DepartureDate) = MONTH(GETDATE()) + YEAR(GETDATE())
AND StageRowNumber = 1 --AND cte.ScheduledDepartureDate IS NOT NULL
--AND cte.ScheduledDepartureAirport IS NOT NULL
GROUP BY StagingFlight,
sac.DepartureDate,
sac.DepartureAirport,
cte.DataFlight,
cte.ScheduledDepartureDate,
cte.ScheduledDepartureAirport
The results are correct, all I need to do is add a condition in the WHERE clause where StagingCabinCrew <> DataCabinCrew AND StagingCockpitCrew <> DataCockpitCrew
If a row appears then we have found an error in the data, I just need helping adding this condition in the WHERE Clause because the columns in the WHERE Clause are referring to a SUM and CASE Function. I just need help manipulating the query so that I can add this WHERE Clause
I will guess you are trying to use an alias in the same query.
You CANT do this, because the alias wont be recognized in the WHERE.
SELECT field1 + field2 as myField
FROM yourTable
WHERE myField > 3
You need to include it in a sub query
with cte2 as (
SELECT field1 + field2 as myField
FROM yourTable
)
SELECT *
FROM cte2
WHERE myField > 3
or repeat the function
SELECT field1 + field2 as myField
FROM yourTable
WHERE field1 + field2 > 3

How to use case statement inside where clause of sql 2000

I have a query that contains a WHERE clause with a CASE statement in it (See code below), somehow it doesn't seem to work.
select * FROM
details
where orgcode in
(case when orgtype='P' then
(SELECT distinct [PCode]
FROM [GPOS_Extract].[dbo].[GP8288List])
else
0 end )
How about
select * FROM details
where (orgtype <> 'P' AND orgcode = 0)
or orgcode in
(
SELECT distinct [PCode]
FROM [GPOS_Extract].[dbo].[GP8288List]
)
Or try this:
SELECT * FROM details
WHERE details.orgcode IN
( SELECT DISTINCT
(CASE WHEN details.orgtype='P'
THEN [GPOS_Extract].[dbo].[GP8288List].PCode
ELSE 0 END)
FROM [GPOS_Extract].[dbo].[GP8288List] )
I think the following is the logic that is equivalent to your attempt:
select *
FROM details
where (orgtype = 'P' and
orgcode in (SELECT distinct [PCode]
FROM [GPOS_Extract].[dbo].[GP8288List]
)
) or
((orgtype <> 'P' or orgtype is NULL) and orgcode = 0);
what about this,
select a.*,case when orgtype='P' then PCode else '0' end FROM
details a
left join [GPOS_Extract].[dbo].[GP8288List] b on a.orgcode=b.PCode
case returns a single value. You are trying to use it as though it returns a result set. What you want is:
select * FROM details d
where (orgtype = 'p'
And exists (Select *
From GPOS_Extract.dbo.GP8288List
Where PCode = d.orgcode))
or (orgtype <> 'p' And orgcode= 0)

counting records on the same table with different values possibly none sql server 2008

I have a inventory table with a condition i.e. new, used, other, and i am query a small set of this data, and there is a possibility that all the record set contains only 1 or all the conditions. I tried using a case statement, but if one of the conditions isn't found nothing for that condition returned, and I need it to return 0
This is what I've tried so far:
select(
case
when new_used = 'N' then 'new'
when new_used = 'U' then 'used'
when new_used = 'O' then 'other'
end
)as conditions,
count(*) as count
from myDB
where something = something
group by(
case
when New_Used = 'N' then 'new'
when New_Used = 'U' then 'used'
when New_Used = 'O' then 'other'
end
)
This returns the data like:
conditions | count
------------------
new 10
used 45
I am trying to get the data to return like the following:
conditions | count
------------------
new | 10
used | 45
other | 0
Thanks in advance
;WITH constants(letter,word) AS
(
SELECT l,w FROM (VALUES('N','new'),('U','used'),('O','other')) AS x(l,w)
)
SELECT
conditions = c.word,
[count] = COUNT(x.new_used)
FROM constants AS c
LEFT OUTER JOIN dbo.myDB AS x
ON c.letter = x.new_used
AND something = something
GROUP BY c.word;
try this -
DECLARE #t TABLE (new_used CHAR(1))
INSERT INTO #t (new_used)
SELECT t = 'N'
UNION ALL
SELECT 'N'
UNION ALL
SELECT 'U'
SELECT conditions, ISNULL(r.cnt, 0) AS [count]
FROM (
VALUES('U', 'used'), ('N', 'new'), ('O', 'other')
) t(c, conditions)
LEFT JOIN (
SELECT new_used, COUNT(1) AS cnt
FROM #t
--WHERE something = something
GROUP BY new_used
) r ON r.new_used = t.c
in output -
new 2
used 1
other 0
You can do it as a cross-tab:
select
sum(case when new_used = 'N' then 1 else 0 end) as N,
sum(case when new_used = 'U' then 1 else 0 end) as U,
sum(case when new_used = 'O' then 1 else 0 end) as Other
from myDB
where something = something