sql returning no rows selected - sql
how can I make this sql query return zero for the count function instead of no rows selected?
select ur.uno, count(*)*5
from userresponse ur, question q
where ur.eno = q.eno
and q.correctanswer = ur.response
and q.qno = ur.qno
and ur.uno = '1'
and q.eno = '1'
group by ur.uno
q.correctanswer = ur.response is never true for this query that's what causes the no row selected, however I want to return zero.
sample data
Note:
- "||" is used to concatenate strings
- each string is between a pair of single quotes.
- each record is between "(" and ")".
- fields are ordered according to fields in tables
- "\n" means a new line
======exams data==========
(1,'Java Programming',60,1)
(3,'Elementary History',10,3)
======questions data===========
(1,1,'Choose the operations that can be performed on String
objects:(A) +\n(B) + =\n(C) -\n(D) %\n(E) ^','B')
(1,2,'What will be the result of the expression\na % b\nwhen a and b
are of type int and their values are a = -17 and b = -6?','A')
(1,3,'What will be the result of the expression\na % b\nwhen a and b
are of type int and their values are a = 10 and b = 6?','B')
(1,4,'Consider the following code:\nint x, y, z\ny = 1\nz = 5\nx = 0
- (++y) + z++\nAfter execution of this, what will be the values of x, y and z?','C')
(1,5,'Identify the statements that are correct:\n(A) int a = 13,
a>>2 = 3\n(B) int b = -8, b>>1 = -4\n(C) int a = 13, a>>>2 = 3\n(D)
int b = -8, b>>>1 = -4','E')
(1,6,'If not assigned a value, a variable of type char has the
following default value:','A')
(1,7,'What will be the value of a after execution of the following
statements:\nint a = 23, b = 34\na = ((a < b) ? (b + a) : (b -
a)','B')
(1,8,'Which of the following is not a hexadecimal number?\n(A)
999\n(B) (hex)23\n(C) 0x556\n(D) 0x1F2','C')
(1,9,'if(check4Biz(storeNum) != null) {}\nReferring to the above,
what datatype could be returned by method check4Biz()?','D')
(1,10,'Select the invalid assignment statements from the
following:\n(A) float x = 238.88\n(B) double y = 0x443\n(C) int n =
(int) true\n(D) long m =778645','A')
(1,11,'int j\nfor(int i=0i<14i++) {\nif(i<10) {\nj = 2 +
i\n}\nSystem.out.println("j: " + j + " i: " + i)\n}\nWhat is WRONG
with the above code?','E')
(1,12,'Consider the following code:\nclass ClassA\n{\npublic static
void main(String args [ ])\n{\nClassB b = classB()\n}\nClassA(int x) {
}\n}\nclass ClassB extends ClassA\n{\n}\nWhat will happen when we
compile and run this code?','A')
(1,13,'The keywords reserved but not used in the initial version of
Java are:\n(A) union\n(B) const\n(C) inner\n(D) goto\n(E) boolean\n(F)
synchronized','C')
(1,14,'We would like to make a member of a class visible in all
subclasses regardless of what package they are in. Which one of the
following keywords would achieve this?','D')
(1,15,'Which of the following are not keywords?\n(A) NULL\n(B)
implements\n(C) protected\n(D) extended\n(E) string','B')
(3,1,'The Battle of Gettysburg was fought during which war?','C')
(3,2,'Neil Armstrong and Buzz Aldrin walked how many \n' ||
'minutes on the moon in 1696?','B')
(3,3,'Which Presidents held office during World War II?','D')
(3,4,'In a communist economic system, people:','B')
(3,5,'Which president did not die while in office?','D')
(3,6,'Which state refused to attend the Constitutional Convention
\n' ||
'in 1787 because it didn''t want the United States government \n' ||
'to interfere with already established state affairs?','A')
(3,7,'Who founded Buddhism?','A')
(3,8,'Where is India?','D')
(3,9,'What is the dominant religion in India?','B')
(3,10,'Near which river did archaeologists find India''s \n' ||
'first civilization?','B')
========== answerOption data ============
(3,8,'A','Australia') (3,8,'B','America') (3,8,'C','Africa')
(3,8,'D','Asia') (3,1,'A','World War II') (3,1,'B','The
Revolutionary War') (3,1,'C','The Civil War') (3,1,'D','World War I')
(3,2,'A','123') (3,2,'B','None') (3,2,'C','10') (3,2,'D','51')
(3,3,'A','Franklin D. Roosevelt') (3,3,'B','Dwight D. Eisenhower')
(3,3,'C','Harry Truman') (3,3,'D','Both A and C') (3,4,'A','Are
forced to work as slaves') (3,4,'B','Work for the common good')
(3,4,'C','Work from home computers') (3,4,'D','Don''t work')
(3,5,'A','John F. Kennedy') (3,5,'B','Franklin D. Roosevelt')
(3,5,'C','Abraham Lincoln') (3,5,'D','Ronald Reagan')
(3,5,'E','James A. Garfield') (3,7,'A','Siddharta Gautama')
(3,7,'B','Jesus Christ') (3,7,'C','Mahatma Gandhi')
(3,7,'D','Muhammad') (3,6,'A','Rhode Island') (3,6,'B','New
Hampshire') (3,6,'C','New Jersey') (3,6,'D','New York')
(3,9,'A','Islam') (3,9,'B','Hinduism') (3,9,'C','Christianity')
(3,9,'D','Buddhism') (3,10,'A','The Tiber River') (3,10,'B','The
Indus River') (3,10,'C','The Yellow River') (3,10,'D','The Nile
River') (1,1,'A','(D) & (E)') (1,1,'B',' (A) & (B)') (1,1,'C','(D)')
(1,1,'D','(A)') (1,1,'E','None of these') (1,2,'A','-17')
(1,2,'B','5') (1,2,'C','3') (1,2,'D','-5') (1,2,'E','None of these')
(1,3,'A','1.66') (1,3,'B','4') (1,3,'C','2') (1,3,'D','1')
(1,3,'E','None of these') (1,4,'A','x = 4, y = 1, z = 5') (1,4,'B',' x
= -7, y = 1, z = 5') (1,4,'C','x = 3, y = 2, z = 6') (1,4,'D',' x = 4, y = 2, z = 6') (1,4,'E',' x = 8, y = 2, z = 1') (1,5,'A','(C) & (D) ')
(1,5,'B',' (A), (B) & (C) ') (1,5,'C','(A), (B), (C) & (D)')
(1,5,'D','(A) & (B) ') (1,5,'E','None of the above')
(1,6,'A','\uffff') (1,6,'B','\u0000') (1,6,'C','" " (space)')
(1,6,'D','\u0001') (1,6,'E','None of the above') (1,7,'A','23')
(1,7,'B','Error. Cannot be executed.') (1,7,'C','57') (1,7,'D','11')
(1,7,'E','34') (1,8,'A','(A), (B) & (C)') (1,8,'B','(C)')
(1,8,'C','(A) & (B) ') (1,8,'D','(A)') (1,8,'E','(D)')
(1,9,'A','Boolean') (1,9,'B','Int') (1,9,'C','String')
(1,9,'D','Char') (1,9,'E','Byte') (1,10,'A','(A) & (C)')
(1,10,'B','(A) & (B)') (1,10,'C','(B) ') (1,10,'D','(B) & (D) ')
(1,10,'E','(D)') (1,11,'A','Integer "j" is not initialized.')
(1,11,'B','Nothing.') (1,11,'C','You cannot declare integer i inside
the for-loop declaration.') (1,11,'D','The syntax of the "if"
statement is incorrect.') (1,11,'E','You cannot print integer values
without converting them to strings.') (1,12,'A','Will compile and run
successfully ') (1,12,'B','Error. ClassA does not define a no-argument
constructor ') (1,12,'C','Error. There is no code in the constructor
ClassA(int x) ') (1,12,'D','Error. ClassB does not define a
no-argument constructor ') (1,12,'E','Error. There is no code in the
class ClassB ') (1,13,'A','(C) & (E) ') (1,13,'B','(B),(C) & (D)')
(1,13,'C','(A), (C) & (E)') (1,13,'D','All of these. ')
(1,13,'E','None of these. ') (1,14,'A','private ') (1,14,'B','public')
(1,14,'C','protected') (1,14,'D','private OR protected')
(1,14,'E','All of the above') (1,15,'A','(C), (D) & (E)')
(1,15,'B','(D) ') (1,15,'C','(A), (D) & (E)') (1,15,'D','(D) & (E) ')
(1,15,'E','(A)')
===== users data ====
(1,'1#gmail.com','','George','Ronald','','','Atlanta','GA','30303')
(2,'2#gmail.com','','Mary','Erikson','','','San Diego','CA','91901')
(3,'3#gmail.com','','John','Washington','','','Atlanta','GA','30314')
====enrolls data=====
(1,1,to_date('2012/02/15 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/22 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(2,1,to_date('2012/02/15 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/22 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(3,1,to_date('2012/02/17 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/24 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(1,3,to_date('2012/02/17 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/24 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(2,3,to_date('2012/02/20 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/27 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
(3,3,to_date('2012/02/20 10:00:00', 'yyyy/mm/dd
hh24:mi:ss'),to_date('2012/02/27 10:00:00', 'yyyy/mm/dd hh24:mi:ss')
===userResponse data====
(1,1,1,'A') (1,1,2,'B') (1,1,3,'A') (1,1,4,'B') (1,1,5,'N')
(1,1,6,'C') (1,1,7,'D') (1,1,8,'A') (1,1,9,'B') (1,1,10,'B')
(1,1,11,'A') (1,1,12,'B') (1,1,13,'A') (1,1,14,'A') (1,1,15,'A')
(2,1,1,'B') (2,1,2,'B') (2,1,3,'E') (2,1,4,'C') (2,1,5,'D')
(2,1,6,'A') (2,1,7,'C') (2,1,8,'B') (2,1,9,'B') (2,1,10,'A')
(2,1,11,'A') (2,1,12,'B') (2,1,13,'B') (2,1,14,'A') (2,1,15,'A')
(3,1,1,'C') (3,1,2,'C') (3,1,3,'D') (3,1,4,'D') (3,1,5,'A')
(3,1,6,'A') (3,1,7,'D') (3,1,8,'D') (3,1,9,'A') (3,1,10,'A')
(3,1,11,'B') (3,1,12,'B') (3,1,13,'A') (3,1,14,'A') (3,1,15,'C')
(1,3,1,'N') (1,3,2,'A') (1,3,3,'A') (1,3,4,'B') (1,3,5,'B')
(1,3,6,'C') (1,3,7,'D') (1,3,8,'A') (1,3,9,'A') (1,3,10,'B')
(2,3,1,'B') (2,3,2,'C') (2,3,3,'A') (2,3,4,'C') (2,3,5,'B')
(2,3,6,'D') (2,3,7,'D') (2,3,8,'D') (2,3,9,'A') (2,3,10,'A')
(3,3,1,'B') (3,3,2,'A') (3,3,3,'A') (3,3,4,'B') (3,3,5,'B')
(3,3,6,'C') (3,3,7,'D') (3,3,8,'A') (3,3,9,'A') (3,3,10,'B')
Then it sounds like you want to do an outer join
select ur.uno, count(q.eno)*5
from userresponse ur
left outer join question q
on( ur.eno = q.eno
and q.correctanswer = ur.response
and q.qno = ur.qno
and q.eno = '1')
where ur.uno = '1'
group by ur.uno
This will return a row for every row in userresponse with a uno of '1' with a count(*) of 0 if there are no matching rows in question.
Try out above Query with ISNULL function:
select ur.uno, NVL(count(*)*5,0)
from userresponse ur, question q
where ur.eno = q.eno
and q.correctanswer = ur.response
and q.qno = ur.qno
and ur.uno = '1'
and q.eno = '1'
group by ur.uno
when ever AND Operator are implementing with the different value on the same column with equality operator the overall condition return NO ROW as AND Operator evaluate on a 1 to 1 with direction towards table to the column...............
Related
Microsoft SQL query to view
I have this complex query that i want to turn into a view. This query comes from https://snippets.cacher.io/snippet/3e84b01b7d52b4ca7807 and i want to save it in a view or even as a table if possible. ` /*##=============================================*/ /*## QUERY BODY */ /*##=============================================*/ /* #region QueryBody */ /* Testing variables !! Need to be commented for Production !! */ -- DECLARE #UserSIDs AS NVARCHAR(10) = 'Disabled'; -- DECLARE #CollectionID AS NVARCHAR(10) = 'SMS00001'; -- DECLARE #Locale AS INT = 2; -- DECLARE #Categories AS NVARCHAR(250) = 'Tools'; -- DECLARE #Compliant AS INT = 0; -- DECLARE #Targeted AS INT = 1; -- DECLARE #Superseded AS INT = 0; -- DECLARE #ArticleID AS NVARCHAR(10) = ''; -- DECLARE #ExcludeArticleIDs AS NVARCHAR(250) = ''; /* Variable declaration */ DECLARE #LCID AS INT = dbo.fn_LShortNameToLCID(#Locale); DECLARE #HelperFunctionExists AS INT = 0; /* Perform cleanup */ IF OBJECT_ID('tempdb..#MaintenanceInfo', 'U') IS NOT NULL DROP TABLE #MaintenanceInfo; /* Check for helper function */ IF OBJECT_ID('[dbo].[ufn_CM_GetNextMaintenanceWindow]') IS NOT NULL SET #HelperFunctionExists = 1; /* Initialize HealthState descriptor table */ DECLARE #HealthState TABLE ( BitMask INT , StateName NVARCHAR(250) ) /* Populate HealthState table */ INSERT INTO #HealthState (BitMask, StateName) VALUES ('0', 'Healthy') , ('1', 'Unmanaged') , ('2', 'Inactive') , ('4', 'Health Evaluation Failed') , ('8', 'Pending Restart') , ('16', 'Update Scan Failed') , ('32', 'Update Scan Late') , ('64', 'No Maintenance Window') , ('128', 'Distant Maintenance Window') , ('256', 'Expired Maintenance Window') /* Initialize ClientState descriptor table */ DECLARE #ClientState TABLE ( BitMask INT , StateName NVARCHAR(100) ) /* Populate ClientState table */ INSERT INTO #ClientState (BitMask, StateName) VALUES ('0', 'No Reboot') , ('1', 'Configuration Manager') , ('2', 'File Rename') , ('4', 'Windows Update') , ('8', 'Add or Remove Feature') CREATE TABLE #MaintenanceInfo ( ResourceID INT , NextServiceWindow DATETIME ) /* Get maintenance data */ IF #HelperFunctionExists = 1 BEGIN WITH Maintenance_CTE AS ( SELECT CollectionMembers.ResourceID , NextServiceWindow.Duration , NextServiceWindow.NextServiceWindow , RowNumber = DENSE_RANK() OVER (PARTITION BY ResourceID ORDER BY NextServiceWindow.NextServiceWindow) , ServiceWindowType , ServiceWindow.Enabled FROM vSMS_ServiceWindow AS ServiceWindow JOIN fn_rbac_FullCollectionMembership(#UserSIDs) AS CollectionMembers ON CollectionMembers.CollectionID = ServiceWindow.SiteID JOIN fn_rbac_Collection(#UserSIDs) AS Collections ON Collections.CollectionID = CollectionMembers.CollectionID AND Collections.CollectionType = 2 -- Device Collections CROSS APPLY ufn_CM_GetNextMaintenanceWindow(ServiceWindow.Schedules, ServiceWindow.RecurrenceType) AS NextServiceWindow WHERE NextServiceWindow.NextServiceWindow IS NOT NULL AND ServiceWindowType <> 5 -- OSD Service ) /* Populate MaintenanceInfo table and remove duplicates */ INSERT INTO #MaintenanceInfo(ResourceID, NextServiceWindow) SELECT ResourceID , NextServiceWindow FROM Maintenance_CTE WHERE RowNumber = 1 END /* Get update data */ ; WITH UpdateInfo_CTE AS ( SELECT ResourceID = Systems.ResourceID , Missing = COUNT(*) FROM fn_rbac_R_System(#UserSIDs) AS Systems JOIN fn_rbac_UpdateComplianceStatus(#UserSIDs) AS ComplianceStatus ON ComplianceStatus.ResourceID = Systems.ResourceID AND ComplianceStatus.Status = 2 -- Filter on 'Required' (0 = Unknown, 1 = NotRequired, 2 = Required, 3 = Installed) JOIN fn_rbac_ClientCollectionMembers(#UserSIDs) AS CollectionMembers ON CollectionMembers.ResourceID = ComplianceStatus.ResourceID JOIN fn_rbac_UpdateInfo(#LCID, #UserSIDs) AS UpdateCIs ON UpdateCIs.CI_ID = ComplianceStatus.CI_ID AND UpdateCIs.IsSuperseded IN (#Superseded) AND UpdateCIs.CIType_ID IN (1, 8) -- Filter on 1 Software Updates, 8 Software Update Bundle (v_CITypes) AND UpdateCIs.ArticleID NOT IN ( -- Filter on ArticleID csv list SELECT VALUE FROM STRING_SPLIT(#ExcludeArticleIDs, ',') ) AND UpdateCIs.Title NOT LIKE ( -- Filter Preview updates '[1-9][0-9][0-9][0-9]-[0-9][0-9]_Preview_of_%' ) JOIN fn_rbac_CICategoryInfo_All(#LCID, #UserSIDs) AS CICategory ON CICategory.CI_ID = ComplianceStatus.CI_ID AND CICategory.CategoryTypeName = 'UpdateClassification' AND CICategory.CategoryInstanceName IN (#Categories) -- Filter on Selected Update Classification Categories LEFT JOIN fn_rbac_CITargetedMachines(#UserSIDs) AS Targeted ON Targeted.ResourceID = ComplianceStatus.ResourceID AND Targeted.CI_ID = ComplianceStatus.CI_ID WHERE CollectionMembers.CollectionID = #CollectionID AND IIF(Targeted.ResourceID IS NULL, 0, 1) IN (#Targeted) -- Filter on 'Targeted' or 'NotTargeted' AND IIF(UpdateCIs.ArticleID = #ArticleID, 1, 0) = IIF(#ArticleID <> '', 1, 0) GROUP BY Systems.ResourceID ) /* Get device info */ SELECT Systems.ResourceID /* Set Health states. You can find the coresponding values in the HealthState table above */ , HealthStates = ( IIF(CombinedResources.IsClient != 1, POWER(1, 1), 0) + IIF( ClientSummary.ClientStateDescription = 'Inactive/Pass' OR ClientSummary.ClientStateDescription = 'Inactive/Fail' OR ClientSummary.ClientStateDescription = 'Inactive/Unknown' , POWER(2, 1), 0) + IIF( ClientSummary.ClientStateDescription = 'Active/Fail' OR ClientSummary.ClientStateDescription = 'Inactive/Fail' , POWER(4, 1), 0 ) + IIF(CombinedResources.ClientState != 0, POWER(8, 1), 0) + IIF(UpdateScan.LastErrorCode != 0, POWER(16, 1), 0) + IIF(UpdateScan.LastScanTime < (SELECT DATEADD(dd, -14, CURRENT_TIMESTAMP)), POWER(32, 1), 0) + IIF(ISNULL(NextServiceWindow, 0) = 0 AND #HelperFunctionExists = 1, POWER(64, 1), 0) + IIF(NextServiceWindow > (SELECT DATEADD(dd, 30, CURRENT_TIMESTAMP)), POWER(128, 1), 0) + IIF(NextServiceWindow < (CURRENT_TIMESTAMP), POWER(256, 1), 0) ) , Missing = ISNULL(Missing, (IIF(CombinedResources.IsClient = 1, 0, NULL))) , Device = ( IIF( SystemNames.Resource_Names0 IS NOT NULL, UPPER(SystemNames.Resource_Names0) , IIF(Systems.Full_Domain_Name0 IS NOT NULL, Systems.Name0 + '.' + Systems.Full_Domain_Name0, Systems.Name0) ) ) , OperatingSystem = ( CASE WHEN OperatingSystem.Caption0 != '' THEN CONCAT( REPLACE(OperatingSystem.Caption0, 'Microsoft ', ''), -- Remove 'Microsoft ' from OperatingSystem REPLACE(OperatingSystem.CSDVersion0, 'Service Pack ', ' SP') -- Replace 'Service Pack ' with ' SP' in OperatingSystem ) ELSE ( /* Workaround for systems not in GS_OPERATING_SYSTEM table */ CASE WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.1%' THEN 'Windows 7' WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.2%' THEN 'Windows 8' WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.3%' THEN 'Windows 8.1' WHEN CombinedResources.DeviceOS LIKE '%Workstation 10.0%' THEN 'Windows 10' WHEN CombinedResources.DeviceOS LIKE '%Server 6.0' THEN 'Windows Server 2008' WHEN CombinedResources.DeviceOS LIKE '%Server 6.1' THEN 'Windows Server 2008R2' WHEN CombinedResources.DeviceOS LIKE '%Server 6.2' THEN 'Windows Server 2012' WHEN CombinedResources.DeviceOS LIKE '%Server 6.3' THEN 'Windows Server 2012 R2' WHEN Systems.Operating_System_Name_And0 LIKE '%Server 10%' THEN ( CASE WHEN CAST(REPLACE(Build01, '.', '') AS INTEGER) > 10017763 THEN 'Windows Server 2019' ELSE 'Windows Server 2016' END ) ELSE Systems.Operating_System_Name_And0 END ) END ) , LastBootTime = ( CONVERT(NVARCHAR(16), OperatingSystem.LastBootUpTime0, 120) ) , PendingRestart = ( CASE WHEN CombinedResources.IsClient = 0 OR CombinedResources.ClientState = 0 THEN NULL ELSE ( STUFF( REPLACE( ( SELECT '#!' + LTRIM(RTRIM(StateName)) AS [data()] FROM #ClientState WHERE BitMask & CombinedResources.ClientState <> 0 FOR XML PATH('') ), ' #!',', ' ), 1, 2, '' ) ) END ) , ClientState = ( CASE CombinedResources.IsClient WHEN 1 THEN ClientSummary.ClientStateDescription ELSE 'Unmanaged' END ) , ClientVersion = CombinedResources.ClientVersion , LastUpdateScan = ( CONVERT(NVARCHAR(16), UpdateScan.LastScanTime, 120) ) , LastScanLocation = NULLIF(UpdateScan.LastScanPackageLocation, '') , LastScanError = NULLIF(UpdateScan.LastErrorCode, 0) , NextServiceWindow = IIF(CombinedResources.IsClient != 1, NULL, CONVERT(NVARCHAR(16), NextServiceWindow, 120)) FROM fn_rbac_R_System(#UserSIDs) AS Systems JOIN fn_rbac_CombinedDeviceResources(#UserSIDs) AS CombinedResources ON CombinedResources.MachineID = Systems.ResourceID LEFT JOIN fn_rbac_RA_System_ResourceNames(#UserSIDs) AS SystemNames ON SystemNames.ResourceID = Systems.ResourceID LEFT JOIN fn_rbac_GS_OPERATING_SYSTEM(#UserSIDs) AS OperatingSystem ON OperatingSystem.ResourceID = Systems.ResourceID LEFT JOIN fn_rbac_CH_ClientSummary(#UserSIDs) AS ClientSummary ON ClientSummary.ResourceID = Systems.ResourceID LEFT JOIN fn_rbac_UpdateScanStatus(#UserSIDs) AS UpdateScan ON UpdateScan.ResourceID = Systems.ResourceID LEFT JOIN #MaintenanceInfo AS Maintenance ON Maintenance.ResourceID = Systems.ResourceID LEFT JOIN UpdateInfo_CTE AS UpdateInfo ON UpdateInfo.ResourceID = Systems.ResourceID JOIN fn_rbac_FullCollectionMembership(#UserSIDs) AS CollectionMembers ON CollectionMembers.ResourceID = Systems.ResourceID WHERE CollectionMembers.CollectionID = #CollectionID AND ( CASE -- Compliant (0 = No, 1 = Yes, 2 = Unknown) WHEN Missing = 0 OR (Missing IS NULL AND Systems.Client0 = 1) THEN 1 -- Yes WHEN Missing > 0 AND Missing IS NOT NULL THEN 0 -- No ELSE 2 -- Unknown END ) IN (#Compliant) /* Perform cleanup */ IF OBJECT_ID('tempdb..#MaintenanceInfo', 'U') IS NOT NULL DROP TABLE #MaintenanceInfo; /* #endregion */ /*##=============================================*/ /*## END QUERY BODY */ /*##=============================================*/ ` Is there an easy way to achieve this? I have tried to look at the official Microsoft documentation but are still not able to convert the query to a view. https://learn.microsoft.com/en-us/sql/t-sql/statements/create-view-transact-sql?view=sql-server-ver16 As I am new to SQL language I am not sure where to start.
So I agree with Larnu, that this probably doesn't make a ton of sense. But there are cases where one might want to be able to run multiple batches of queries / procedural code from an object that's as consumable as a view. I've done this once in a case where I needed to maximize my options for performance tuning without losing the consumability of the object. So for the sake of when it does make sense, this is something you could do: Wrap your code in a stored procedure. Use OPENQUERY() to call your procedure. Wrap the OPENQUERY() call in a view. Limitations with this methodology is it's rather static: You can't pass parameters to your stored procedure If you use temp tables in your stored procedure, then you need to use the WITH RESULT SETS clause to explicitly define the shape of your result set The procedure can only return one result set The SQL Server Engine puts a hard-coded cardinality estimate of 10,000 against OPENQUERY(). So in cases where your procedure returns a lot more rows (typically an order of magnitude or more) than 10,000, e.g. 1 million rows, then you may experience some performance issues with joining the wrapper view to other objects. Example: -- Step 1: Wrap the procedural code in a stored procedure CREATE PROCEDURE dbo.RunSomeCode AS BEGIN CREATE TABLE #Results (ID INT, SomeValue VARCHAR(100)); DECLARE #SomeVariable INT = 0; WHILE (#SomeVariable < 5) BEGIN SET #SomeVariable = #SomeVariable + 1; INSERT INTO #Results (ID, SomeValue) SELECT ID, SomeValue FROM SomeTable WHERE ID = #SomeVariable END SELECT ID, SomeValue FROM #Results; END GO -- Step 2 & 3: Wrap an OPENQUERY() call to the procedure in a view. CREATE VIEW dbo.SomeView AS SELECT ID, SomeValue FROM OPENQUERY ( ' LocalServerName, EXEC dbo.RunSomeCode WITH RESULT SETS (( ID INT, SomeValue VARCHAR(100) )) ' ); Voila, you can now execute the procedure by SELECTing from the view: SELECT ID, SomeValue FROM dbo.SomeView;
How to query Oracle grouping?
I have such a problem and I don't know how to solve it, can you help me? t The query returns a result that is shown on the photo and I want to get it to be shown in one line instead of many based on type of age. https://imgur.com/a/OA6CBpa with x as ( select ai.invoice_id, ai.invoice_num, ai.invoice_amount, ai.amount_paid, trial.entity_id, trial.acctd_amount, trial.entered_amount, trial.gl_date, aps.amount_remaining, aps.gross_amount, aps.due_date, aps.payment_status_flag, trial.gl_date - aps.due_date dni_opoznienia from ap_invoices_all ai, xla.xla_transaction_entities xte, ( select nvl (tr.applied_to_entity_id, tr.source_entity_id) entity_id, tr.source_application_id application_id, sum (nvl (tr.acctd_unrounded_cr, 0)) - sum (nvl (tr.acctd_unrounded_dr, 0)) acctd_amount, sum (nvl (tr.entered_unrounded_cr, 0)) - sum (nvl (tr.entered_unrounded_dr, 0)) entered_amount, max(tr.gl_date) gl_date from xla.xla_trial_balances tr where 1=1 and tr.definition_code = 'AP_200_1001' and tr.source_application_id = 200 and tr.gl_date <= fnd_date.canonical_to_date('2019-12-13') -- Data KG group by nvl (tr.applied_to_entity_id, tr.source_entity_id), tr.source_application_id ) trial, ap_payment_schedules_all aps where 1=1 and ai.invoice_id = 3568325 and nvl(xte.source_id_int_1, -99) = ai.invoice_id and xte.ledger_id = 1001 and xte.entity_code = 'AP_INVOICES' and xte.entity_id = trial.entity_id and xte.application_id = trial.application_id and ai.invoice_id = aps.invoice_id ) select x.invoice_id, x.invoice_num, x.entity_id, x.acctd_amount, x.gl_date, x.amount_remaining, x.gross_amount, x.due_date, x.payment_status_flag, x.dni_opoznienia, aapl.days_start, aapl.days_to, case when x.dni_opoznienia between aapl.days_start and aapl.days_to then x.acctd_amount else 0 end przedzial from x, ap_aging_periods aap, ap_aging_period_lines aapl where 1=1 and aap.period_name = 'TEST 5 okresow' and aap.aging_period_id = aapl.aging_period_id
Based on your comment I guess you need the below select * from (select x.invoice_id, x.invoice_num, x.entity_id, x.acctd_amount, x.gl_date, x.amount_remaining, x.gross_amount, x.due_date, x.payment_status_flag, x.dni_opoznienia, aapl.days_start, aapl.days_to, case when x.dni_opoznienia between aapl.days_start and aapl.days_to then x.acctd_amount else 0 end przedzial from x, ap_aging_periods aap, ap_aging_period_lines aapl where 1=1 and aap.period_name = 'TEST 5 okresow' and aap.aging_period_id = aapl.aging_period_id) where przedzial > 0;
Adding a new row to empty dataframe located in data lake
I created a empty dataframe table to location at Delta by using this code below: deltaResultPath = "/ml/streaming-analysis/delta/Result" # Create Delta Lake table sqlq = "CREATE TABLE stockDailyPrices_delta USING DELTA LOCATION '" + deltaResultPath + "'" spark.sql(sqlq) I am new to spark and do not fully understand sparkSQL code. What I want to do is instead of inserting values from another dataframe, I would like to add values generated in python script. Something like modifying the code from: insert_sql = "insert into stockDailyPrices_delta select f.* from stockDailyPrices f where f.price_date >= '" + price_date_min.strftime('%Y-%m-%d') + "' and f.price_date <= '" + price_date_max.strftime('%Y-%m-%d') + "'" spark.sql(insert_sql) to Time = 10 cpu_temp = 3 dsp_temp = 5 insert_sql = "insert into df (Time, cpu_temp, dsp_temp) values (%s, %s, %s)" spark.sql(insert_sql) However, I see the error following: org.apache.spark.sql.catalyst.parser.ParseException: ParseException: "\nmismatched input 'Time' expecting {'(', 'SELECT', 'FROM', 'DESC', 'VALUES', 'TABLE', 'INSERT', 'DESCRIBE', 'MAP', 'MERGE', 'UPDATE', 'REDUCE'}(line 1, pos 16)\n\n== SQL ==\ninsert into df (Time, cpu_temp, dsp_temp) values (%s, %s, %s)\n----------------^^^\n" How can I fix this code?
I could make it work with something like this spark.sql("insert into Result_delta select {} as Time, {} as cpu_temp, {} as dsp_temp".format(Time, cpu_temp, dsp_temp))
Linq - SQL query conversion
Can some one help me to convert this query to linq? I dont know how to use union and then sum in linq. SELECT Patientname, SUM(A)AS Trec FROM (SELECT Pm.Patientname, COUNT(*)AS A FROM Facilitycheckinholdorder Fcho INNER JOIN Medordertype Mot ON Fcho.Orderseq = Mot.Orderseq JOIN Patientmaster Pm ON Mot.Patientseq = Pm.Patientseq AND Fcho.Filleddate BETWEEN '2011-09-01 00:00:00:000' AND '2012-10-16 00:00:00:000' AND Mot.Facilityid = 139 GROUP BY Pm.Patientname UNION ALL SELECT Pm.Patientname, COUNT(*)AS A FROM Rxqdeliveryholdorder Rdho INNER JOIN Medordertype Mot ON Rdho.Orderseq = Mot.Orderseq JOIN Patientmaster Pm ON Mot.Patientseq = Pm.Patientseq AND Rdho.Filleddate BETWEEN '2011-09-01 00:00:00:000' AND '2012-10-16 00:00:00:000' AND Mot.Facilityid = 139 GROUP BY Pm.Patientname ) AS Trec GROUP BY Patientname;
In fact this is not a real question, but I've tried my best... var lst1 = from fhco in facilitycheckinholdorder join mot in meordertype on mot.orderseq equals fhco.orderseq join pm in patientmaster on mot.patientseq equals pm.patientseq where fcho.FilledDate >= new DateTime(2011, 9, 1) fcho.FilledDate <= new DateTime(2012, 10, 16) select pm; var lst2 = from rdho in rxqdeliveryholdorder join mot in meordertype on rdho.orderseq equals mot.orderseq join pm in patientmaster on moit.patientseq equals pm.patientseq where fcho.FilledDate >= new DateTime(2011, 9, 1) fcho.FilledDate <= new DateTime(2012, 10, 16) select pm; var res = from item in lst1.Union(lst2) select new { Name = item.patientname, Count = lst1.Count() + lst2.Count() };
Key points: Your outermost query seems redundant. Your names are not common C# style, and it makes them difficult to read. UNION ALL corresponds to Concat, not Union. Getting the Concat out of the way early lets you streamline the query. You could do this in the SQL. . var result = from order in Queryable.Concat( FacilityCheckInHoldOrder.Select(o => new { o.OrderSeq, o.FilledDate }), RxqDeliveryHoldOrder .Select(o => new { o.OrderSeq, o.FilledDate })) where order.FilledDate >= new DateTime(2011, 9, 1) && order.FilledDate < new DateTime(2012, 10, 16) join type in MedOrderType.Where(t => t.FacilityID == 139) on order.OrderSeq equals type.OrderSeq join patient in PatientMaster on type.PatientSeq equals patient.PatientSeq group by patient.PatientName into grp select new { PatientName = grp.Key, Trec = grp.Count() };
sql statement how to keep null value
This query here is executed on 3 tables(students) one which makes a zero on the exam so his q.correctanswer != ur.response, how can I keep the 0 value in my output. When i execute this statement it only gives me two values instead of 3 for each student. select count(*) as Test1 from users u, question q, userresponse ur where q.eno = '1' and q.eno = ur.eno and q.qno = ur.qno and ur.response = q.correctanswer and u.uno = ur.uno group by u.uno sample data: Note: - "||" is used to concatenate strings - each string is between a pair of single quotes. - each record is between "(" and ")". - fields are ordered according to fields in tables - "\n" means a new line ======exams data========== (1,'Java Programming',60,1) (3,'Elementary History',10,3) ======questions data=========== (1,1,'Choose the operations that can be performed on String objects:(A) +\n(B) + =\n(C) -\n(D) %\n(E) ^','B') (1,2,'What will be the result of the expression\na % b\nwhen a and b are of type int and their values are a = -17 and b = -6?','A') (1,3,'What will be the result of the expression\na % b\nwhen a and b are of type int and their values are a = 10 and b = 6?','B') (1,4,'Consider the following code:\nint x, y, z\ny = 1\nz = 5\nx = 0 - (++y) + z++\nAfter execution of this, what will be the values of x, y and z?','C') (1,5,'Identify the statements that are correct:\n(A) int a = 13, a>>2 = 3\n(B) int b = -8, b>>1 = -4\n(C) int a = 13, a>>>2 = 3\n(D) int b = -8, b>>>1 = -4','E') (1,6,'If not assigned a value, a variable of type char has the following default value:','A') (1,7,'What will be the value of a after execution of the following statements:\nint a = 23, b = 34\na = ((a < b) ? (b + a) : (b - a)','B') (1,8,'Which of the following is not a hexadecimal number?\n(A) 999\n(B) (hex)23\n(C) 0x556\n(D) 0x1F2','C') (1,9,'if(check4Biz(storeNum) != null) {}\nReferring to the above, what datatype could be returned by method check4Biz()?','D') (1,10,'Select the invalid assignment statements from the following:\n(A) float x = 238.88\n(B) double y = 0x443\n(C) int n = (int) true\n(D) long m =778645','A') (1,11,'int j\nfor(int i=0i<14i++) {\nif(i<10) {\nj = 2 + i\n}\nSystem.out.println("j: " + j + " i: " + i)\n}\nWhat is WRONG with the above code?','E') (1,12,'Consider the following code:\nclass ClassA\n{\npublic static void main(String args [ ])\n{\nClassB b = classB()\n}\nClassA(int x) { }\n}\nclass ClassB extends ClassA\n{\n}\nWhat will happen when we compile and run this code?','A') (1,13,'The keywords reserved but not used in the initial version of Java are:\n(A) union\n(B) const\n(C) inner\n(D) goto\n(E) boolean\n(F) synchronized','C') (1,14,'We would like to make a member of a class visible in all subclasses regardless of what package they are in. Which one of the following keywords would achieve this?','D') (1,15,'Which of the following are not keywords?\n(A) NULL\n(B) implements\n(C) protected\n(D) extended\n(E) string','B') (3,1,'The Battle of Gettysburg was fought during which war?','C') (3,2,'Neil Armstrong and Buzz Aldrin walked how many \n' || 'minutes on the moon in 1696?','B') (3,3,'Which Presidents held office during World War II?','D') (3,4,'In a communist economic system, people:','B') (3,5,'Which president did not die while in office?','D') (3,6,'Which state refused to attend the Constitutional Convention \n' || 'in 1787 because it didn''t want the United States government \n' || 'to interfere with already established state affairs?','A') (3,7,'Who founded Buddhism?','A') (3,8,'Where is India?','D') (3,9,'What is the dominant religion in India?','B') (3,10,'Near which river did archaeologists find India''s \n' || 'first civilization?','B') ========== answerOption data ============ (3,8,'A','Australia') (3,8,'B','America') (3,8,'C','Africa') (3,8,'D','Asia') (3,1,'A','World War II') (3,1,'B','The Revolutionary War') (3,1,'C','The Civil War') (3,1,'D','World War I') (3,2,'A','123') (3,2,'B','None') (3,2,'C','10') (3,2,'D','51') (3,3,'A','Franklin D. Roosevelt') (3,3,'B','Dwight D. Eisenhower') (3,3,'C','Harry Truman') (3,3,'D','Both A and C') (3,4,'A','Are forced to work as slaves') (3,4,'B','Work for the common good') (3,4,'C','Work from home computers') (3,4,'D','Don''t work') (3,5,'A','John F. Kennedy') (3,5,'B','Franklin D. Roosevelt') (3,5,'C','Abraham Lincoln') (3,5,'D','Ronald Reagan') (3,5,'E','James A. Garfield') (3,7,'A','Siddharta Gautama') (3,7,'B','Jesus Christ') (3,7,'C','Mahatma Gandhi') (3,7,'D','Muhammad') (3,6,'A','Rhode Island') (3,6,'B','New Hampshire') (3,6,'C','New Jersey') (3,6,'D','New York') (3,9,'A','Islam') (3,9,'B','Hinduism') (3,9,'C','Christianity') (3,9,'D','Buddhism') (3,10,'A','The Tiber River') (3,10,'B','The Indus River') (3,10,'C','The Yellow River') (3,10,'D','The Nile River') (1,1,'A','(D) & (E)') (1,1,'B',' (A) & (B)') (1,1,'C','(D)') (1,1,'D','(A)') (1,1,'E','None of these') (1,2,'A','-17') (1,2,'B','5') (1,2,'C','3') (1,2,'D','-5') (1,2,'E','None of these') (1,3,'A','1.66') (1,3,'B','4') (1,3,'C','2') (1,3,'D','1') (1,3,'E','None of these') (1,4,'A','x = 4, y = 1, z = 5') (1,4,'B',' x = -7, y = 1, z = 5') (1,4,'C','x = 3, y = 2, z = 6') (1,4,'D',' x = 4, y = 2, z = 6') (1,4,'E',' x = 8, y = 2, z = 1') (1,5,'A','(C) & (D) ') (1,5,'B',' (A), (B) & (C) ') (1,5,'C','(A), (B), (C) & (D)') (1,5,'D','(A) & (B) ') (1,5,'E','None of the above') (1,6,'A','\uffff') (1,6,'B','\u0000') (1,6,'C','" " (space)') (1,6,'D','\u0001') (1,6,'E','None of the above') (1,7,'A','23') (1,7,'B','Error. Cannot be executed.') (1,7,'C','57') (1,7,'D','11') (1,7,'E','34') (1,8,'A','(A), (B) & (C)') (1,8,'B','(C)') (1,8,'C','(A) & (B) ') (1,8,'D','(A)') (1,8,'E','(D)') (1,9,'A','Boolean') (1,9,'B','Int') (1,9,'C','String') (1,9,'D','Char') (1,9,'E','Byte') (1,10,'A','(A) & (C)') (1,10,'B','(A) & (B)') (1,10,'C','(B) ') (1,10,'D','(B) & (D) ') (1,10,'E','(D)') (1,11,'A','Integer "j" is not initialized.') (1,11,'B','Nothing.') (1,11,'C','You cannot declare integer i inside the for-loop declaration.') (1,11,'D','The syntax of the "if" statement is incorrect.') (1,11,'E','You cannot print integer values without converting them to strings.') (1,12,'A','Will compile and run successfully ') (1,12,'B','Error. ClassA does not define a no-argument constructor ') (1,12,'C','Error. There is no code in the constructor ClassA(int x) ') (1,12,'D','Error. ClassB does not define a no-argument constructor ') (1,12,'E','Error. There is no code in the class ClassB ') (1,13,'A','(C) & (E) ') (1,13,'B','(B),(C) & (D)') (1,13,'C','(A), (C) & (E)') (1,13,'D','All of these. ') (1,13,'E','None of these. ') (1,14,'A','private ') (1,14,'B','public') (1,14,'C','protected') (1,14,'D','private OR protected') (1,14,'E','All of the above') (1,15,'A','(C), (D) & (E)') (1,15,'B','(D) ') (1,15,'C','(A), (D) & (E)') (1,15,'D','(D) & (E) ') (1,15,'E','(A)') ===== users data ==== (1,'1#gmail.com','','George','Ronald','','','Atlanta','GA','30303') (2,'2#gmail.com','','Mary','Erikson','','','San Diego','CA','91901') (3,'3#gmail.com','','John','Washington','','','Atlanta','GA','30314') ====enrolls data===== (1,1,to_date('2012/02/15 10:00:00', 'yyyy/mm/dd hh24:mi:ss'),to_date('2012/02/22 10:00:00', 'yyyy/mm/dd hh24:mi:ss') (2,1,to_date('2012/02/15 10:00:00', 'yyyy/mm/dd hh24:mi:ss'),to_date('2012/02/22 10:00:00', 'yyyy/mm/dd hh24:mi:ss') (3,1,to_date('2012/02/17 10:00:00', 'yyyy/mm/dd hh24:mi:ss'),to_date('2012/02/24 10:00:00', 'yyyy/mm/dd hh24:mi:ss') (1,3,to_date('2012/02/17 10:00:00', 'yyyy/mm/dd hh24:mi:ss'),to_date('2012/02/24 10:00:00', 'yyyy/mm/dd hh24:mi:ss') (2,3,to_date('2012/02/20 10:00:00', 'yyyy/mm/dd hh24:mi:ss'),to_date('2012/02/27 10:00:00', 'yyyy/mm/dd hh24:mi:ss') (3,3,to_date('2012/02/20 10:00:00', 'yyyy/mm/dd hh24:mi:ss'),to_date('2012/02/27 10:00:00', 'yyyy/mm/dd hh24:mi:ss') ===userResponse data==== (1,1,1,'A') (1,1,2,'B') (1,1,3,'A') (1,1,4,'B') (1,1,5,'N') (1,1,6,'C') (1,1,7,'D') (1,1,8,'A') (1,1,9,'B') (1,1,10,'B') (1,1,11,'A') (1,1,12,'B') (1,1,13,'A') (1,1,14,'A') (1,1,15,'A') (2,1,1,'B') (2,1,2,'B') (2,1,3,'E') (2,1,4,'C') (2,1,5,'D') (2,1,6,'A') (2,1,7,'C') (2,1,8,'B') (2,1,9,'B') (2,1,10,'A') (2,1,11,'A') (2,1,12,'B') (2,1,13,'B') (2,1,14,'A') (2,1,15,'A') (3,1,1,'C') (3,1,2,'C') (3,1,3,'D') (3,1,4,'D') (3,1,5,'A') (3,1,6,'A') (3,1,7,'D') (3,1,8,'D') (3,1,9,'A') (3,1,10,'A') (3,1,11,'B') (3,1,12,'B') (3,1,13,'A') (3,1,14,'A') (3,1,15,'C') (1,3,1,'N') (1,3,2,'A') (1,3,3,'A') (1,3,4,'B') (1,3,5,'B') (1,3,6,'C') (1,3,7,'D') (1,3,8,'A') (1,3,9,'A') (1,3,10,'B') (2,3,1,'B') (2,3,2,'C') (2,3,3,'A') (2,3,4,'C') (2,3,5,'B') (2,3,6,'D') (2,3,7,'D') (2,3,8,'D') (2,3,9,'A') (2,3,10,'A') (3,3,1,'B') (3,3,2,'A') (3,3,3,'A') (3,3,4,'B') (3,3,5,'B') (3,3,6,'C') (3,3,7,'D') (3,3,8,'A') (3,3,9,'A') (3,3,10,'B') Thanks,
What I think you're asking is "how many questions did any user get right?" If so, based on the query you have - and the fact that there's no direct relation between users and questions - I've come up with the following: select u.uno, sum(case ur.response when null then 0 else 1 end) as Test1 from question q cross join users u left join userresponse ur on q.eno = ur.eno and q.qno = ur.qno and q.correctanswer = ur.response and u.uno = ur.uno where q.eno = '1' group by u.uno So we do a cartesion join between users and questions, because we don't have a better way to join them. We then do an left outer join against the userresponse table; unless everything matches correctly, the user either didn't answer the question or answered it wrong. We cast whether or not that value's null to a 0 if null and 1 if if it's not, so the sum of those is the number of correct answers per user.
If I've understood your query correctly, the following ought to work. It uses the old Oracle join syntax: SELECT u.uno, COUNT(*) FROM users u, userresponse ur, question q WHERE u.uno = ur.uno AND ur.response = q.correctanswer(+) AND ur.eno = q.eno(+) AND ur.qno = q.qno(+) AND q.eno(+) = 1 GROUP BY u.uno
I think that you are trying to get all users and the associated quiz score. If I understood correctly, then using appropriate joins clauses, you can easily get the expected results: select u.uno, count (ur.response) as NumberAnswered, count (q.correctanswer) as NumberCorrect from users u join userresponse ur --inner join means we limit user rows to users who have responses on u.uno = ur.uno left outer join question q --outer join means we look for row data, but don't exclude users based on the fact that the row doesn't match the join conditions on ur.response = q.correctanswer and q.eno = 1 --only include rows where the question.eno value is 1(?) and q.eno = ur.eno --only include rows where question.eno and userresponse.eno are the same (the answer was correct) group by u.uno