Add a WHERE clause in a complex SQL query - sql-server

I want to pass a ShowRoomId value to the query below. The Employees table has a ShowRoomId column.
How can I do it?
My SQL query is as following:
SELECT *
FROM Employees A
OUTER APPLY (SELECT TOP 1 *
FROM EmployeeBasics B
WHERE (A.EmployeeID = B.EmployeeID)
ORDER BY B.BasicUpdateDate DESC) AS B
OUTER APPLY (
SELECT C.EmployeeId , count(*) AS TotalAbsent
FROM EmployeeAbsents C
WHERE C.AbsentDate BETWEEN '2016-05-01' AND '2016-05-30' AND A.EmployeeID = C.EmployeeID
GROUP BY C.EmployeeId
) AS C
OUTER APPLY (
SELECT EmployeeId,
SUM(CASE WHEN TransctionTypeId = 1 THEN Amount ELSE 0 END) AS Payment,
SUM(CASE WHEN TransctionTypeId = 2 THEN Amount ELSE 0 END) AS RecoverSalary,
SUM(CASE WHEN TransctionTypeId = 3 THEN Amount ELSE 0 END) AS RecoverCash
FROM dbo.EmployeeAdvances D
WHERE A.EmployeeID = D.EmployeeID
GROUP BY EmployeeId
) AS D

Simply use a WHERE clause at the end as following:
... YOUR SELECT ...
WHERE Col = ...YourCondition...
OR
Use WITH keyword to keep your current SELECT-statement in a cte. Then do your query on it.
WITH cte AS
(
... YOUR SELECT ...
)
SELECT *
FROM cte
WHERE Col = ...YourCondition...
OR
You can add your SELECT-statement in to parentheses and name it with an allias name. So you can do query on it too.
SELECT *
FROM
(
... YOUR SELECT ...
) t
WHERE t.Col = ...YourCondition...

As per Giorgi Nakeuri's advice, I added the WHERE clause at the end of the statement.
And it works for me. Revised code is here:
SELECT *
FROM Employees A
OUTER APPLY (SELECT TOP 1 *
FROM EmployeeBasics B
WHERE (A.EmployeeID = B.EmployeeID)
ORDER BY B.BasicUpdateDate DESC) AS B
OUTER APPLY (
SELECT C.EmployeeId , count(*) AS TotalAbsent
FROM EmployeeAbsents C
WHERE C.AbsentDate BETWEEN '2016-05-01' AND '2016-05-30' AND A.EmployeeID = C.EmployeeID
GROUP BY C.EmployeeId
) AS C
OUTER APPLY (
SELECT EmployeeId,
SUM(CASE WHEN TransctionTypeId = 1 THEN Amount ELSE 0 END) AS Payment,
SUM(CASE WHEN TransctionTypeId = 2 THEN Amount ELSE 0 END) AS RecoverSalary,
SUM(CASE WHEN TransctionTypeId = 3 THEN Amount ELSE 0 END) AS RecoverCash
FROM dbo.EmployeeAdvances D
WHERE A.EmployeeID = D.EmployeeID
GROUP BY EmployeeId
) AS D
WHERE A.ShowRoomId = 2

Related

T-SQL, repeated same scalar subquery performance in views

Below is a simple query that retrieves Students and their exam results. The same student can take the same exam multiple times. The subqueries retrieve the latest exam results for each student. As you can see, the Line X (which retrieves the latest Exam ID) is exactly the same in every subquery for each row. How to store or cache the result of Line X to prevent three times execution for each row?
I cannot use stored procedure or functions for this task, it has to be a VIEW for additional filtering.
SELECT S.*,
(
SELECT COUNT(*) FROM ExamAnswers WHERE
IsCorrectAnswer IS NOT NULL AND
IsCorrectAnswer = 1 AND
ExamID =
(SELECT TOP(1) ID FROM Exams E WHERE E.StudentID = S.ID ORDER BY ID DESC) --Line X
) CorrectAnswerCount,
(
SELECT COUNT(*) FROM ExamAnswers EA WHERE
EA.IsCorrectAnswer IS NOT NULL AND
EA.IsCorrectAnswer = 0 AND
EA.ExamID =
(SELECT TOP(1) ID FROM Exams E WHERE E.StudentID = S.ID ORDER BY ID DESC) --Line X
) WrongAnswerCount,
(
SELECT COUNT(*) FROM ExamAnswers WHERE
IsCorrectAnswer IS NULL AND
ExamID =
(SELECT TOP(1) ID FROM Exams E WHERE E.StudentID = S.ID ORDER BY ID DESC) --Line X
) UnansweredQuestionCount
FROM Students S
You can do it like this
SELECT S.*,
CA.*
FROM Students S
CROSS APPLY (SELECT SUM(CASE WHEN IsCorrectAnswer = 1 THEN 1 ELSE 0 END) AS CorrectAnswerCount,
SUM(CASE WHEN IsCorrectAnswer = 0 THEN 1 ELSE 0 END) AS WrongAnswerCount,
SUM(CASE WHEN IsCorrectAnswer IS NULL THEN 1 ELSE 0 END) AS UnansweredQuestionCount
FROM ExamAnswers EA
WHERE EA.ExamID = (SELECT TOP(1) ID
FROM Exams E
WHERE E.StudentID = S.ID
ORDER BY ID DESC)) CA
What about this approach :
WITH
T AS
(
SELECT Student_id,
SUM(CASE IsCorrectAnswer WHEN 1 THEN 1 END) AS COUNT_TRUE,
SUM(CASE IsCorrectAnswer WHEN 0 THEN 1 END) AS COUNT_FALSE,
SUM(CASE WHEN IsCorrectAnswer IS NULL THEN 1 END) AS COUNT_UNKNOWN
FROM ExamAnswers AS EA
WHERE EA.ExamID = (SELECT MAX(ID)
FROM Exams E
WHERE E.StudentID = S.ID)
GROUP BY Student_id
)
SELECT S.*, COUNT_TRUE, COUNT_FALSE, COUNT_UNKNOWN
FROM Students AS S
JOIN T ON S.ID = T.Student_id

SUM with CASE counts duplicate rows in SQL GROUP BY

I'm trying to do a SUM against all items which match a certain condition, like so:
SELECT l.Building_Name,
SUM(CASE WHEN s.Date >= '20180930' THEN 1 ELSE 0 END) Validated,
COUNT(DISTINCT s.id) Total
FROM Lab_Space s
JOIN Locations l ON s.Building_Code = l.Building_Code
GROUP BY l.Building_Name
The COUNT there is correct, and will say something like 20 because I can put the DISTINCT s.id in there. However, my SUM ends up with something like 1500. This is because when I do the JOIN rows are duplicated multiple times, and thus the SUM is counting against each one.
How can I do a SUM/CASE like this but make sure it only applies to distinct rows?
s.id l.building_name s.date
1 JF 2018-11-10
1 JF 2018-11-10
2 JF 2018-12-12
So if I have data like that, I'm going to get my count properly of 2, but validate will say 3 because the id of 1 appears twice due to doing a JOIN
You can edit this code of temp table if you deem fit.
create table #temp_Lab_Space
([Date] date null
,Building_Code int null
)
create table #temp_Locations
( Building_Code int null
,Building_Name varchar(10) null
)
insert into #temp_Lab_Space values
('2018-11-10',1)
,('2018-11-10', 1)
,('2018-12-12' , 1)
insert into #temp_Locations values
(1, 'JF')
select Building_Name,
SUM(CASE WHEN Date >= '20180930' THEN 1 ELSE 0 END) Validated,
COUNT(DISTINCT Building_Code) Total
from (
select distinct l.Building_Name, s.Building_Code, s.Date
,Rank_1 = rank() over(partition by l.Building_Name order by s.Date asc)
FROM #temp_Lab_Space s
JOIN #temp_Locations l ON s.Building_Code = l.Building_Code
) a
group by Building_Name
wild guess
select l.Building_Name
, count(s.Id)
, sum(s.Validated)
from Locations l
cross apply ( select s.Id
, max(case
when s.Date >= '20180930' then 1
else 0
end) as Validated
from Lab_Space s
where s.Building_Code = l.Building_Code
group by s.Id) s
group by l.Building_Name
should give you the distinct space.id and a flag whether it is validated.

Get Data Based on Row

I have table tblControlFlag which have the data as Below.
I want to write a single query which give me the output as 1 when
RRO_FLAG=1
AND SEAL_FLAG=1
AND TEST_CODE='VLXXXXXX'
AND SERIAL_NO='k7jpevdt'
If any of the Flag value is mismatched then the query return me null.
Till now i had tried Sub Query , Exist but couldn't achieve the result.
So does it achievable , if yes then how ?
Please help me out . Thanks
Your question is not clear to me. Not sure how you wanted the result.
Anyway,
use GROUP BY with HAVING() condition. This will returns the SERIAL_NO that matches the condition
select SERIAL_NO
from tblControlFlag
group by SERIAL_NO
HAVING MAX(CASE WHEN FLAG_NAME = 'PRO_FLAG' THEN FLAG_VALUE END) = '1'
AND MAX(CASE WHEN FLAG_NAME = 'SEAL_FLAG' THEN FLAG_VALUE END) = '1'
AND MAX(CASE WHEN FLAG_NAME = 'TESTCODE' THEN FLAG_VALUE END) = 'VLXXXXXX'
or if you want the resultant column 1 or 0
select SERIAL_NO,
MATCH = CASE WHEN MAX(CASE WHEN FLAG_NAME = 'PRO_FLAG' THEN FLAG_VALUE END) = '1'
AND MAX(CASE WHEN FLAG_NAME = 'SEAL_FLAG' THEN FLAG_VALUE END) = '1'
AND MAX(CASE WHEN FLAG_NAME = 'TESTCODE' THEN FLAG_VALUE END) = 'VLXXXXXX'
THEN 1
ELSE 0
END
from tblControlFlag
group by SERIAL_NO
Use this query
Select Case WHEN Count(*)>0 then 1 else null END AS TesColumn From tblControlFlag when RRO_FLAG=1 AND SEAL_FLAG=1 AND TEST_CODE='VLXXXXXX' AND SERIAL_NO='k7jpevdt'
Since you have tried sub-query and EXISTS, here is very straight-forward query but may not run fast.
SELECT COUNT(DISTINCT SERIAL_NO)
FROM #tblControlFlag AS T1
WHERE EXISTS (SELECT * FROM #tblControlFlag T2 WHERE T1.SERIAL_NO = T2.SERIAL_NO AND T2.FLAG_NAME = 'RRO_FLAG' AND FLAG_VALUE = '1')
AND EXISTS (SELECT * FROM #tblControlFlag T2 WHERE T1.SERIAL_NO = T2.SERIAL_NO AND T2.FLAG_NAME = 'SEAL_FLAG' AND FLAG_VALUE = '1')
AND EXISTS (SELECT * FROM #tblControlFlag T2 WHERE T1.SERIAL_NO = T2.SERIAL_NO AND T2.FLAG_NAME = 'TEST_CODE' AND FLAG_VALUE = 'VLXXXXXX')
As there is no duplicated FLAG_NAME per SERIAL_NO, you could convert row to columns and perform the check RRO_FLAG=1 AND SEAL_FLAG=1 AND TEST_CODE='VLXXXXXX' AND SERIAL_NO='k7jpevdt'
SELECT *
FROM (
SELECT * FROM #tblControlFlag
) AS T
PIVOT (
MAX(FLAG_VALUE) FOR FLAG_NAME IN (RRO_FLAG, [SEAL_FLAG], [TEST_CODE])
) AS P
WHERE RRO_FLAG=1 AND SEAL_FLAG=1 AND TEST_CODE='VLXXXXXX' AND SERIAL_NO='k7jpevdt'

how to add left join with CTE , check my query

i have following query i want add my query left join with CTE how do this please help me because i have driver id i want second last driver id but i want add left join with CTE
select d.Id,d.DriverNo,d.DriverName,TransId=dc.Id,dc.FromDate,dc.ToDate,dc.IsPaid,
Active=(case when (dc.weekoff is null or dc.weekoff=0) then 'Active' else 'Off' end),
Rent=(case when (IsNull(dc.CommissionTotal,0))> IsNull(dc.AccJobsTotal,0) then IsNull(dc.CommissionTotal,0)-(IsNull(dc.AccJobsTotal,0)) else 0 end),
BalanceDue=IsNull(dc.OldBalance,0),
AgentCommission=IsNull(dc.AgentFeesTotal,0),
PDA= (case when (dc.weekoff is null or dc.weekoff=0) then (IsNull(dc.PDARent,0)+IsNull(dc.CollectionDeliveryCharges,0)) else 0 end),
Total=(case when (IsNull(dc.CommissionTotal,0))> IsNull(dc.AccJobsTotal,0) then IsNull(dc.CommissionTotal,0)-(IsNull(dc.AccJobsTotal,0)) else 0 end)
+((IsNull(dc.OldBalance,0))
+((IsNull(dc.AgentFeesTotal,0)))
+(case when (dc.weekoff is null or dc.weekoff=0) then (IsNull(dc.PDARent,0)+IsNull(dc.CollectionDeliveryCharges,0)) else 0 end))
from Fleet_Driver d
inner join Fleet_DriverCommision dc
on d.Id=dc.DriverId
where dc.Id in (select Max(Id) from Fleet_DriverCommision
group by DriverId) as T1
left join on
> LEFT JOIN WITH CTE
With cte as
(select AgentFeesTotal,DriverId,Row_Number()over(Partition by DriverID order by Transdate desc) as Rn,
count(1)over(Partition by DriverID) as cnt from Fleet_DriverCommision)
Select AgentFeesTotal,DriverId
from cte
Where (Rn = 2 and cnt > 1) or (Rn = 1 and cnt = 1)
This is example
with cte
as
(select AgentFeesTotal,DriverId,Row_Number()over(Partition by DriverID order by Transdate desc) as Rn,
count(1)over(Partition by DriverID) as cnt from Fleet_DriverCommision)
Select AgentFeesTotal,DriverId
from cte
Where (Rn = 2 and cnt > 1) or (Rn = 1 and cnt = 1)
select t2.DriverNo from Fleet_Driver t2
left join
cte c
on c.DriverId=t2.Id
It looks like you are struggling with the syntax for using CTEs. The CTE declaration needs to happen before the rest of the query and then behaves like another table. Also note that the WITH statement must be the first statement or follow a semi-colon. This should get you on the right track. Also be sure to check the examples in the MSDN documentation.
--With statement first - must follow ; if there are multiple statements...
With cte as
(select AgentFeesTotal,DriverId,
Row_Number()over(Partition by DriverID order by Transdate desc) as Rn,
count(1)over(Partition by DriverID) as cnt
from Fleet_DriverCommision
)
-- ...then select statement...
select d.Id,d.DriverNo,d.DriverName,TransId=dc.Id,
dc.FromDate,dc.ToDate,dc.IsPaid,
Active=(case when (dc.weekoff is null or dc.weekoff=0) then 'Active' else 'Off' end),
Rent=(case when (IsNull(dc.CommissionTotal,0))> IsNull(dc.AccJobsTotal,0) then IsNull(dc.CommissionTotal,0)-(IsNull(dc.AccJobsTotal,0)) else 0 end),
BalanceDue=IsNull(dc.OldBalance,0),
AgentCommission=IsNull(dc.AgentFeesTotal,0),
PDA= (case when (dc.weekoff is null or dc.weekoff=0) then (IsNull(dc.PDARent,0)+IsNull(dc.CollectionDeliveryCharges,0)) else 0 end),
Total=(case when (IsNull(dc.CommissionTotal,0))> IsNull(dc.AccJobsTotal,0) then IsNull(dc.CommissionTotal,0)-(IsNull(dc.AccJobsTotal,0)) else 0 end)
+((IsNull(dc.OldBalance,0))
+((IsNull(dc.AgentFeesTotal,0)))
+(case when (dc.weekoff is null or dc.weekoff=0) then (IsNull(dc.PDARent,0)+IsNull(dc.CollectionDeliveryCharges,0)) else 0 end))
from Fleet_Driver d
inner join Fleet_DriverCommision dc
on d.Id=dc.DriverId
--...join in cte as a normal table
left join cte
on --join criteria here
where dc.Id in (select Max(Id) from Fleet_DriverCommision
group by DriverId) as T1
--move the remainder of the logic into your query
Select AgentFeesTotal,DriverId
from cte
Where (Rn = 2 and cnt > 1) or (Rn = 1 and cnt = 1)

Case statement in sql using other selected columns in the same statement

I would like to know if the following is possible in SQL server 2005. Column A and B are calculated using other case statements in my actual stored proc. I don't want to repeat the same for another field unnecessarily. If this is not syntactically possible, any other ideas?
SELECT A, B, CASE WHEN column1='1' THEN A ELSE B END Col1.
Modified version of actual query provided as requested. CTE kind of seems to be tough in this model. WANNABE is the column I want to accomplish in the sub select statement.
SELECT 1 AS Region, 'Test',
CAST(Work AS NUMERIC(18,2)) Work,
Work + 2 AS Work2,
WANNABE
FROM
(
SELECT
ROW_NUMBER() OVER(PARTITION BY G.Value, C.C, FR.Mod1 ORDER BY FR.Date DESC, FG.Date DESC, FC.Date DESC) ROW,
CASE WHEN COALESCE(FR.Mod1, '') = '' THEN '' ELSE FR.Mod1 END Mod1,
CASE WHEN #var1=1 AND #var2 = 1 THEN FR.Col1 * G.Value
WHEN #var1=1 AND #var2 = 0 THEN FP.Col1 * G.Value END Work,
CASE WHEN 1=1 THEN Work ELSE 1 END WANNABE,
(
SELECT Col3
FROM Table2
WHERE c = FR.Value
) AS Custom
FROM MainTable FR
JOIN #C C ON FR.Col2 = C.Col2
LEFT JOIN Function1(#VersionDate) cv ON cv.Code = C.Code
LEFT JOIN Function2(#VersionDate) hv ON hv.Code = C.Code
LEFT JOIN #G G ON 1 = 1
LEFT JOIN SubTable1 FG ON FG.Number = G.Value, 2 AND FG.Date = #VersionDate
LEFT JOIN SubTable2 FO ON FO.Number = G.Value
AND FO.Date = #VersionDate AND FO.Code = FR.Code AND FR.Mod1 = FO.Mod1
LEFT JOIN SubTable3 FP ON FP.Code = FR.Code AND FP.VersionDate = #Versiondate
AND CASE WHEN DATALENGTH(FR.Mod1) = 0 THEN '00' ELSE FR.Mod1 END = CASE WHEN DATALENGTH(FP.Mod1) = 0 THEN '00' ELSE FP.Mod1 END
LEFT JOIN SubTable4 FC ON FC.Date = #VersionDate
WHERE FR.Date = #VersionDate
) x
WHERE x.Row = 1
AND RTRIM(LTRIM(x.Col1)) IN ('', '2')
You can define the A,B column aliases in a CTE then reference them in an outer select.
;WITH CTE AS
(
SELECT CASE ... END AS A,
CASE ... END AS B,
column1
FROM your_table
)
SELECT A,
B,
CASE WHEN column1='1' THEN A ELSE B END Col1
FROM CTE
Similarly you can also define them in a CROSS APPLY that is sometimes a bit less verbose.
A silly example just to show the syntax is
SELECT A,
B,
CASE WHEN type='P' THEN A ELSE B END Col1
FROM master..spt_values
CROSS APPLY (SELECT CASE WHEN number %2 = 1 THEN 1 END,
CASE WHEN number %2 = 0 THEN 0 END) T(A,B)
Following your update you can replace the derived table with a CTE and nest CTEs as follows
;WITH x as
(
SELECT
ROW_NUMBER() OVER(PARTITION BY G.Value, C.Code, FR.Mod1 ORDER BY FR.Date DESC, FG.Date DESC, FC.Date DESC) ROW,
...<snip>
WHERE FR.Date = #VersionDate
),
x2 As
(
SELECT *,
CASE WHEN 1=1 THEN Work ELSE 1 END WANNABE
FROM x
)
SELECT 1 AS Region, 'Test',
CAST(Work AS NUMERIC(18,2)) Work,
Work + 2 AS Work2,
WANNABE
FROM x2
WHERE x2.Row = 1
AND RTRIM(LTRIM(x2.Col1)) IN ('', '2')
Yeah it is posible, but how is all your sql statement? You can use the case statement in the select statement as you are using it.
Something like this
SELECT SUM((CASE WHEN column1='1' THEN 10 ELSE 0 END)) AS A, SUM((CASE WHEN column1='2' THEN 10 ELSE 0 END)) AS B
FROM YourTable

Resources