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'
Related
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
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)
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
I have a Table With the following definition :
CREATE TABLE [dbo].[Due] (
[dueID] INT IDENTITY (1, 1) NOT NULL,
[dueTypeID] INT NOT NULL,
[vehicleID] INT NOT NULL,
[dueDate] DATE NULL,
...
Here I want to generate a query which would give an output as
VehicleID Type1.dueDate Type2.dueDate Type3.dueDate ...
(the due dates should be the highest for that vehicle for that due type)
I have written the following query to do this :
select vehicleNumber, A.dueDate, B.dueDate, C.dueDate, D.dueDate, E.dueDate, F.dueDate
FROM Vehicle INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '1' GROUP BY Due.vehicleID) As A ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '2' GROUP BY Due.vehicleID) As B ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '3' GROUP BY Due.vehicleID) As C ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '4' GROUP BY Due.vehicleID) As D ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '5' GROUP BY Due.vehicleID) As E ON Vehicle.vehicleID = A.vehicleID INNER JOIN
(SELECT Max(dueDate) as dueDate,vehicleID from Due where dueTypeID = '6' GROUP BY Due.vehicleID) As F ON Vehicle.vehicleID = A.vehicleID
The problem is, the vehicle which does not have a due date for a particular type is taking the value of some other vehicle. Please help me figure out how this can be solved, also if I am doing this the right way or whether there is some better way to do this?
(sorry in case the question is repetitive as I tried looking for it but couldn't find the right keywords to search the problem)
Thanks a lot for helping me out.
Try this:
select vehicleNumber,
Max(case When dueTypeID = '1' Then dueDate Else null end) Typ1dueDate,
Max(case When dueTypeID = '2' Then dueDate Else null end) Typ2dueDate,
Max(case When dueTypeID = '3' Then dueDate Else null end) Typ3dueDate,
Max(case When dueTypeID = '4' Then dueDate Else null end) Typ4dueDate,
Max(case When dueTypeID = '5' Then dueDate Else null end) Typ5dueDate,
Max(case When dueTypeID = '6' Then dueDate Else null end) Typ6dueDate
FROM Due d join Vehicle v
On v.vehicleId = d.vehicleId
Group By v.vehicleNumber
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