SQL Stuff from Subquery - sql-server

I have a query that returns a list of services and ContractorIDs. I need to stuff these services into a field to join them with another select statement by ContractorID, but I can't figure out how to do it.
The Select that lists the services is "
SELECT DISTINCT SM.ContractorID,
CASE WHEN S.bitRestrictedSelection = 1
THEN S.vchDescription + '*'
ELSE S.vchDescription
END AS vchDescription
FROM tblAscServiceRegionToOperator SRTO
INNER JOIN tblServiceMatrix SM
ON SRTO.OperatorID = 12624
AND SM.ServiceRegionID = SRTO.ServiceRegionID
AND SM.bitPrimaryService = 1
INNER JOIN tblServices S
ON S.ServiceID = SM.ServiceID
This produces the following:
In the example, for Contractor #16 He has 4 services I need to put them in one field called services by joining with another Select statement
I tried the following, but I get errors:
Select DISTINCT CompanyID, vchCompanyName as CompanyName,vchFIDNumber,vchPrimContactName, vchPrimContactEmail
,stuff((','
SELECT DISTINCT
SM.ContractorID,
CASE WHEN S.bitRestrictedSelection = 1
THEN S.vchDescription + '*'
ELSE S.vchDescription
END AS vchDescription
FROM tblAscServiceRegionToOperator SRTO
INNER JOIN tblServiceMatrix SM
ON SRTO.OperatorID = 12624
AND SM.ServiceRegionID = SRTO.ServiceRegionID
AND SM.bitPrimaryService = 1
INNER JOIN tblServices S
ON S.ServiceID = SM.ServiceID
FOR XML PATH('')
), 1, 1, '') as Services from tblCompany
Any assistance is greatly appreciated!!!

The following query would work:
SELECT SS.contractor Contractor,
STUFF((SELECT '; ' + US.vchdescription
FROM ServicesList US
WHERE US.contractor = SS.contractor
FOR XML PATH('')), 1, 1, '') [Services]
FROM ServicesList SS
GROUP BY SS.contractor
ORDER BY 1
I have created a table and inserted there two rows for contractor = 16, for you to get the idea.
You can use the suggestion given to you in the comments, to wrap the first select into a CTE and then perform the STUFF function on that CTE.
You can check a demo of this query here.

Related

CASE Statement causing execute time to sky rocket

There are two distinct databases where I work. In creating a report (utilizing TSQL) to share between departments, it was requested to have a field to show the information from the primary database (information kept on the college's database) had also been inputted into a second database (that a specific department uses for information communications with federal program). Without checking the second database with the case statement the query for the rest of the information takes less than a second. With the case statement (in which CTEs where created to conduct the check), it has run for 15 minutes and not finished before I manually ended the execution. Here is the code (CASE statement currently commented out):
With POWERFAIDS_CHECK as
(
Select distinct NAME_MASTER.ID_NUM,
(CAST (NAME_MASTER.ID_NUM as VARCHAR) + CAST (EX_SCHOLARSHIP_RECIPIENTS.AID_ELEMENT as VARCHAR) ) as CHECK_ID
From NAME_MASTER
JOIN EX_SCHOLARSHIP_RECIPIENTS on NAME_MASTER.ID_NUM = EX_SCHOLARSHIP_RECIPIENTS.ID_NUM
JOIN SCHOLARSHIP on EX_SCHOLARSHIP_RECIPIENTS.AID_ELEMENT = SCHOLARSHIP.AID_ELEMENT
JOIN PF_FUND_CDE_MSTR on EX_SCHOLARSHIP_RECIPIENTS.AID_ELEMENT = PF_FUND_CDE_MSTR.RPT_CATEGORY
JOIN PowerFAIDS_Production.dbo.student on NAME_MASTER.ID_NUM = PowerFAIDS_Production.dbo.student.alternate_id
JOIN PowerFAIDS_Production.dbo.funds on PF_FUND_CDE_MSTR.FUND_CDE = PowerFAIDS_Production.dbo.funds.fund_ledger_number
JOIN PowerFAIDS_Production.dbo.stu_award_year on PowerFAIDS_Production.dbo.student.student_token = PowerFAIDS_Production.dbo.stu_award_year.student_token
JOIN PowerFAIDS_Production.dbo.stu_award on PowerFAIDS_Production.dbo.stu_award_year.stu_award_year_token = PowerFAIDS_Production.dbo.stu_award.stu_award_year_token
JOIN YEAR_TERM_TABLE on (YEAR_TERM_TABLE.YR_CDE = EX_SCHOLARSHIP_RECIPIENTS.YR_CDE) and (YEAR_TERM_TABLE.TRM_CDE = EX_SCHOLARSHIP_RECIPIENTS.TRM_CDE)
Where EX_SCHOLARSHIP_RECIPIENTS.YR_CDE = '2021'
and EX_SCHOLARSHIP_RECIPIENTS.TRM_CDE = 'FA'
and YEAR_TERM_TABLE.TRM_BEGIN_DTE = PowerFAIDS_Production.dbo.stu_award.award_period_begin_dt
and EX_SCHOLARSHIP_RECIPIENTS.AWARD_AMT = PowerFAIDS_Production.dbo.stu_award.actual_amt
and stu_award.status = 'A'
),
AWARDED_SCHOLARSHIPS as
(Select distinct NAME_MASTER.ID_NUM, (NAME_MASTER.FIRST_NAME + ' ' + NAME_MASTER.LAST_NAME) as STUDENT_NAME,
SCHOLARSHIP.DESCRIPTION,
Format (EX_SCHOLARSHIP_RECIPIENTS.AWARD_AMT, 'C','en-us') as AWARD_AMT,
EX_SCHOLARSHIP_RECIPIENTS.COMMENTS,
YR_DESC, TRM_DESC, EX_SCHOLARSHIP_RECIPIENTS.AID_ELEMENT,
(CAST (NAME_MASTER.ID_NUM as VARCHAR) + CAST (EX_SCHOLARSHIP_RECIPIENTS.AID_ELEMENT as VARCHAR) ) as CHECK_ID,
NAME_MASTER.LAST_NAME, NAME_MASTER.FIRST_NAME
From NAME_MASTER
JOIN EX_SCHOLARSHIP_RECIPIENTS on NAME_MASTER.ID_NUM = EX_SCHOLARSHIP_RECIPIENTS.ID_NUM
JOIN SCHOLARSHIP on EX_SCHOLARSHIP_RECIPIENTS.AID_ELEMENT = SCHOLARSHIP.AID_ELEMENT
JOIN YEAR_DEF on EX_SCHOLARSHIP_RECIPIENTS.YR_CDE = YEAR_DEF.YR_CDE
JOIN TERM_DEF on EX_SCHOLARSHIP_RECIPIENTS.TRM_CDE = TERM_DEF.TRM_CDE
Where EX_SCHOLARSHIP_RECIPIENTS.TRM_CDE = 'FA'
and EX_SCHOLARSHIP_RECIPIENTS.YR_CDE = '2021'
and EX_SCHOLARSHIP_RECIPIENTS.AID_ELEMENT not between '5000' and '5999'
)
Select distinct AWARDED_SCHOLARSHIPS.ID_NUM, STUDENT_NAME,
AWARDED_SCHOLARSHIPS.DESCRIPTION, AWARDED_SCHOLARSHIPS.AWARD_AMT,
--CASE
-- WHEN AWARDED_SCHOLARSHIPS.CHECK_ID not in (Select CHECK_ID from POWERFAIDS_CHECK)
-- THEN 'No'
-- ELSE 'Yes'
--END as Processed_FA_Award,
AWARDED_SCHOLARSHIPS.COMMENTS,
AWARDED_SCHOLARSHIPS.YR_DESC, AWARDED_SCHOLARSHIPS.TRM_DESC, AWARDED_SCHOLARSHIPS.LAST_NAME, AWARDED_SCHOLARSHIPS.FIRST_NAME
From AWARDED_SCHOLARSHIPS
LEFT OUTER JOIN POWERFAIDS_CHECK on AWARDED_SCHOLARSHIPS.ID_NUM = POWERFAIDS_CHECK.ID_NUM
Where AWARDED_SCHOLARSHIPS.ID_NUM in (Select ID_NUM from AWARDED_SCHOLARSHIPS)
Order by AWARDED_SCHOLARSHIPS.DESCRIPTION, LAST_NAME, FIRST_NAME
Any insights much appreciated, thanks!
It's hard to give a definitive answer here without knowing what your data and indexes look like. If you can share your the execution plan for both versions of your query it would be way easier to give you a clear answer.
You can share you execution plans here: https://www.brentozar.com/pastetheplan/
Without the execution plan here are a couple of ideas to try:
EXISTS often performs better than IN/NOT IN
CASE WHEN EXISTS (SELECT * FROM POWERFAIDS_CHECK WHERE CHECK_ID = AWARDED_SCHOLARSHIPS.CHECK_ID) THEN [...]
Adding a new CTE that contains the subset of data you need might help:
), VALID_CHECK_IDS AS ( SELECT DISTINCT CHECK_ID FROM POWER_FAIDS_CHECK )
Then use this CTE in your case statement.
Add a second join to POWERFAIDS_CHECK
LEFT JOIN POWERFAIDS_CHECK AS VALIDCHECKID ON AWARDED_SCHOLARSHIPS.CHECK_ID = POWERFAIDS_CHECK.CHECK_ID
and update your case to
CASE WHEN VALIDCHECKID.CHECK_ID IS NOT NULL THEN 'No' ELSE 'Yes' [...]

How to use alias in where clause in SQL Server

I have following query and i am getting perfect result what i want but i want to use stManufacturerPartReference alias in where clause condition Like following second query but it gives me error.
WITH ProductsCTE (inProductId, inCategoryId, stCategory, stManufacturers, inCompanyId, stERPId,stManufacturerPartReference,
stProductName, stProductNumber, stModel, stFileLink, stImage, dcPrice,dcStandardPrice, dcOnHandQty,dcQtyOnPO,dtEstimatedShipDate, dcWeight, inSyncStatus, dtLastSyncDate,
inErrorRetry,flgIsActive, flgIsDeleted, inCreatedBy, inModifiedBy, dtModificationDate, dtCreationDate, inRecordCount)
AS (
SELECT
product.inProductId,
product.inCategoryId,
product.stCategory,
product.stManufacturers,
product.inCompanyId,
product.stERPId,
product.stProductName,
STUFF((SELECT ', ' + PM.stManufacturerPartReference
FROM tblProductManufacturers PM
JOIN tblProducts Product on PM.inProductId = Product.inProductId
JOIN tblManufacturers M on M.inManufacturerId = PM.inManufacturerId
WHERE PM.inProductId=product.inProductId
ORDER BY M.stManufacturer
FOR XML PATH('')), 1, 1, '') as stManufacturerPartReference,
product.stProductNumber,
product.stModel,
product.stFileLink,
product.stImage,
product.dcPrice,
product.dcStandardPrice,
product.dcOnHandQty,
product.dcQtyOnPO,
product.dtEstimatedShipDate,
product.dcWeight,
product.inSyncStatus,
product.dtLastSyncDate,
product.inErrorRetry,
product.flgIsActive,
product.flgIsDeleted,
product.inCreatedBy,
product.inModifiedBy,
product.dtModificationDate,
product.dtCreationDate,
CAST((COUNT(product.inProductId) OVER()) AS BIGINT) AS inRecordCount
FROM tblProducts Product WITH (NOLOCK)
WHERE 1=1
AND product.flgIsDeleted <> 1
AND flgIsHistoricItem <> 1 AND (product.inCompanyId = 1) )
SELECT P.inProductId,
P.inCategoryId,
P.stCategory,
P.stManufacturers,
P.stManufacturerPartReference,
P.inCompanyId,
P.stERPId,
P.stProductName,
P.stProductNumber,
P.stModel,
P.stFileLink,
P.stImage,
P.dcPrice,
P.dcStandardPrice,
P.dcOnHandQty,
P.dcQtyOnPO,
P.dtEstimatedShipDate,
P.dcWeight,
P.inSyncStatus,
P.dtLastSyncDate,
P.inErrorRetry,
P.flgIsActive,
P.flgIsDeleted,
P.inCreatedBy,
P.inModifiedBy,
P.dtModificationDate,
P.dtCreationDate,
P.inRecordCount
FROM ProductsCTE P
ORDER BY stCategory ASC
OFFSET (1 - 1) * 1000 ROWS
FETCH NEXT 1000 ROWS ONLY;
i want to use stManufacturerPartReference in Where Clause Like Following.
WITH ProductsCTE (inProductId, inCategoryId, stCategory, stManufacturers, inCompanyId, stERPId,stManufacturerPartReference,
stProductName, stProductNumber, stModel, stFileLink, stImage, dcPrice,dcStandardPrice, dcOnHandQty,dcQtyOnPO,dtEstimatedShipDate, dcWeight, inSyncStatus, dtLastSyncDate,
inErrorRetry,flgIsActive, flgIsDeleted, inCreatedBy, inModifiedBy, dtModificationDate, dtCreationDate, inRecordCount)
AS (
SELECT
product.inProductId,
product.inCategoryId,
product.stCategory,
product.stManufacturers,
product.inCompanyId,
product.stERPId,
product.stProductName,
STUFF((SELECT ', ' + PM.stManufacturerPartReference
FROM tblProductManufacturers PM
JOIN tblProducts Product on PM.inProductId = Product.inProductId
JOIN tblManufacturers M on M.inManufacturerId = PM.inManufacturerId
WHERE PM.inProductId=product.inProductId
ORDER BY M.stManufacturer
FOR XML PATH('')), 1, 1, '') as stManufacturerPartReference,
product.stProductNumber,
product.stModel,
product.stFileLink,
product.stImage,
product.dcPrice,
product.dcStandardPrice,
product.dcOnHandQty,
product.dcQtyOnPO,
product.dtEstimatedShipDate,
product.dcWeight,
product.inSyncStatus,
product.dtLastSyncDate,
product.inErrorRetry,
product.flgIsActive,
product.flgIsDeleted,
product.inCreatedBy,
product.inModifiedBy,
product.dtModificationDate,
product.dtCreationDate,
CAST((COUNT(product.inProductId) OVER()) AS BIGINT) AS inRecordCount
FROM tblProducts Product WITH (NOLOCK)
WHERE 1=1
AND product.flgIsDeleted <> 1
AND flgIsHistoricItem <> 1 AND (product.inCompanyId = 1) AND stManufacturerPartReference LIKE '%ABC DEF%' )
SELECT P.inProductId,
P.inCategoryId,
P.stCategory,
P.stManufacturers,
P.stManufacturerPartReference,
P.inCompanyId,
P.stERPId,
P.stProductName,
P.stProductNumber,
P.stModel,
P.stFileLink,
P.stImage,
P.dcPrice,
P.dcStandardPrice,
P.dcOnHandQty,
P.dcQtyOnPO,
P.dtEstimatedShipDate,
P.dcWeight,
P.inSyncStatus,
P.dtLastSyncDate,
P.inErrorRetry,
P.flgIsActive,
P.flgIsDeleted,
P.inCreatedBy,
P.inModifiedBy,
P.dtModificationDate,
P.dtCreationDate,
P.inRecordCount
FROM ProductsCTE P
ORDER BY stCategory ASC
OFFSET (1 - 1) * 1000 ROWS
FETCH NEXT 1000 ROWS ONLY;
But it Gives me Error "Invalid column name 'stManufacturerPartReference'."
So how can i use alias in where clause please help.
thanks.
I would do instead :
SELECT *, STUFF(stManufacturerPartReference, 1, 1, '') AS stManufacturerPartReference
FROM . . . .
. . . . CROSS APPLY
( SELECT ', ' + PM.stManufacturerPartReference
FROM tblProductManufacturers PM JOIN
tblProducts Product
ON PM.inProductId = Product.inProductId JOIN
tblManufacturers M
ON M.inManufacturerId = PM.inManufacturerId
WHERE PM.inProductId=product.inProductId
FOR XML PATH('')
) tt(stManufacturerPartReference)
WHERE . . . AND
stManufacturerPartReference LIKE '%ABC DEF%';
You need to learn about the order of execution in a SQL query: https://sqlbolt.com/lesson/select_queries_order_of_execution
WHERE comes immediately after FROM, and therefore any aliases are not available to filter on.
As it's wrapped in a CTE, filter on stManufacturerPartReference in the query after it.
WITH ProductsCTE (inProductId, inCategoryId, stCategory, stManufacturers, inCompanyId, stERPId,stManufacturerPartReference,
stProductName, stProductNumber, stModel, stFileLink, stImage, dcPrice,dcStandardPrice, dcOnHandQty,dcQtyOnPO,dtEstimatedShipDate, dcWeight, inSyncStatus, dtLastSyncDate,
inErrorRetry,flgIsActive, flgIsDeleted, inCreatedBy, inModifiedBy, dtModificationDate, dtCreationDate, inRecordCount)
AS (
SELECT
product.inProductId,
product.inCategoryId,
product.stCategory,
product.stManufacturers,
product.inCompanyId,
product.stERPId,
product.stProductName,
STUFF((SELECT ', ' + PM.stManufacturerPartReference
FROM tblProductManufacturers PM
JOIN tblProducts Product on PM.inProductId = Product.inProductId
JOIN tblManufacturers M on M.inManufacturerId = PM.inManufacturerId
WHERE PM.inProductId=product.inProductId
ORDER BY M.stManufacturer
FOR XML PATH('')), 1, 1, '') as stManufacturerPartReference,
product.stProductNumber,
product.stModel,
product.stFileLink,
product.stImage,
product.dcPrice,
product.dcStandardPrice,
product.dcOnHandQty,
product.dcQtyOnPO,
product.dtEstimatedShipDate,
product.dcWeight,
product.inSyncStatus,
product.dtLastSyncDate,
product.inErrorRetry,
product.flgIsActive,
product.flgIsDeleted,
product.inCreatedBy,
product.inModifiedBy,
product.dtModificationDate,
product.dtCreationDate,
CAST((COUNT(product.inProductId) OVER()) AS BIGINT) AS inRecordCount
FROM tblProducts Product WITH (NOLOCK)
WHERE 1=1
AND product.flgIsDeleted 1
AND flgIsHistoricItem 1 AND (product.inCompanyId = 1) )
SELECT P.inProductId,
P.inCategoryId,
P.stCategory,
P.stManufacturers,
P.stManufacturerPartReference,
P.inCompanyId,
P.stERPId,
P.stProductName,
P.stProductNumber,
P.stModel,
P.stFileLink,
P.stImage,
P.dcPrice,
P.dcStandardPrice,
P.dcOnHandQty,
P.dcQtyOnPO,
P.dtEstimatedShipDate,
P.dcWeight,
P.inSyncStatus,
P.dtLastSyncDate,
P.inErrorRetry,
P.flgIsActive,
P.flgIsDeleted,
P.inCreatedBy,
P.inModifiedBy,
P.dtModificationDate,
P.dtCreationDate,
P.inRecordCount
FROM ProductsCTE P
WHERE P.stManufacturerPartReference LIKE '%ABC DEF%'
ORDER BY stCategory ASC
OFFSET (1 - 1) * 1000 ROWS
FETCH NEXT 1000 ROWS ONLY;
You have to use outer apply or cross apply (select .. AS stManufacturerPartReference) and if your server is 2017 you could use String_AGG function to get list of values instead of for xml clause.

How to select a field when it is not in GroupBy clause

I do not want to group by "BimeName.IssueDate" field in this select and I do not know how to do it.
If I don't specify this field in GroupBy clause I will get an error.
Msg 8120, Level 16, State 1, Line 2 Column 'BimeName.IssueDate' is
invalid in the select list because it is not contained in either an
aggregate function or the GROUP BY clause.
Please help me!
SELECT
BimeName.IssueDate,
sum(BimeName.Premium) as Permium,
TypeOfInsurances.TypeOfInsurance + ' ' +
InsuranceKinds.KindOfInsurance as KindOfInsurance,
InsuranceAgents.NameOfInsurance,
InsuranceAgents.Representation + ' ' +
InsuranceAgents.AgentCode as Agent
from
BimeName
Inner Join InsuranceKinds ON InsuranceKinds.Id = BimeName.KindOfInsuranceId
Inner Join TypeOfInsurances ON TypeOfInsurances.Id = InsuranceKinds.TypeOfInsuranceId
Inner Join InsuranceAgents ON InsuranceAgents.Id = TypeOfInsurances.InsuranceAgentId
where
BimeName.IssueDate BETWEEN '2010-01-01' AND '2017-01-30'
group by InsuranceAgents.Representation, InsuranceAgents.NameOfInsurance, InsuranceAgents.AgentCode , BimeName.IssueDate , TypeOfInsurances.TypeOfInsurance , InsuranceKinds.KindOfInsurance
Just leave out the date field from select, if you, like you said, don't need it.
SELECT
sum(BimeName.Premium) as Permium,
TypeOfInsurances.TypeOfInsurance + ' ' +
InsuranceKinds.KindOfInsurance as KindOfInsurance,
InsuranceAgents.NameOfInsurance,
InsuranceAgents.Representation + ' ' +
InsuranceAgents.AgentCode as Agent
from
BimeName
Inner Join InsuranceKinds ON InsuranceKinds.Id = BimeName.KindOfInsuranceId
Inner Join TypeOfInsurances ON TypeOfInsurances.Id = InsuranceKinds.TypeOfInsuranceId
Inner Join InsuranceAgents ON InsuranceAgents.Id = TypeOfInsurances.InsuranceAgentId
where
BimeName.IssueDate BETWEEN '2010-01-01' AND '2017-01-30'
group by
InsuranceAgents.Representation,
InsuranceAgents.NameOfInsurance,
InsuranceAgents.AgentCode,
TypeOfInsurances.TypeOfInsurance,
InsuranceKinds.KindOfInsurance
You can have fields in where clause that are not in group by.
It doesn't make any sense. Imagine it has different values for field BimeName.IssueDate in a same group, so which value must be selected for that category? should think about it again.

Create View - Declare a variable

I am creating a view that is using that STUFF function. I want to put the result of STUFF in a variable for my view. The problem I am having is declaring my variable. It gives me the message "Incorrect Syntax near 'DECLARE'. Expecting '(' or SELECT." I already have the '(' in there. I have tried putting a BEGIN before it. I have tried putting it after the SELECT word. But nothing seems to work and I cannot find a solution in my search. I am using SQL Server 2012
CREATE VIEW [AQB_OB].[GISREQUESTEDBURNS]
AS
(DECLARE #CONDITIONS AS varchar(20)
SET #CONDITIONS = (SELECT DISTINCT BD.[RequestedBurnsID]
,[ConditionsReasonsID] = STUFF((SELECT ', ' + CONVERT(VARCHAR (20),[ConditionsReasonsID]) FROM [AQB_OB].[BurnDecisions] WHERE [RequestedBurnsID]= BD.[RequestedBurnsID] ORDER BY [RequestedBurnsID] ASC
FOR XML PATH ('')) , 1 , 1, '') FROM
[AQB_OB].[BurnDecisions] BD)
SELECT RB.[RequestedBurnsID] AS REQUESTEDBURNID
,BUY.[BurnYear] AS BURNYEAR
,CY.[CurrentYear] AS CURRENTYEAR
,RB.[BurnSitesID] AS BURNSITESID
,[BurnerID] AS BURNERID
,[Contact] AS CONTACT
,[BurnDecision] AS BURNDECISION
,RB.[Comment] AS COMMENT
,#CONDITIONS AS CONDITIONS
FROM [AQB_MON].[AQB_OB].[RequestedBurns] RB
LEFT join AQB_MON.[AQB_OB].[PileDryness] PD on RB.[PileDrynessID] = PD.[PileDrynessID]
inner join AQB_MON.[AQB_OB].[BurnYear] BUY on BUY.BurnYearID = BP.BurnYearID
inner join AQB_MON.[AQB_OB].[CurrentYear] CY on CY.CurrentYearID = BUY.CurrentYearID
GO
You can't declare variables in a view. Could you make it into a function or stored procedure?
Edit - you might also be able to put something into a CTE (Common Table Expression) and keep it as a view.
e.g.
WITH conditions as
(
... do the STUFF here
)
SELECT blah
FROM blah
INNER JOIN conditions
(or CROSS JOIN conditions if its just one row, I can't quite decipher what your data is like)
Here is a sample query that uses a CTE (Common Table Expression) to nicely emulate internal variable construction, as described by James Casey. You can test-run it in your version of SQL Server.
CREATE VIEW vwImportant_Users AS
WITH params AS (
SELECT
varType='%Admin%',
varMinStatus=1)
SELECT status, name
FROM sys.sysusers, params
WHERE status > varMinStatus OR name LIKE varType
SELECT * FROM vwImportant_Users
yielding output:
status name
12 dbo
0 db_accessadmin
0 db_securityadmin
0 db_ddladmin
also via JOIN
WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
SELECT status, name
FROM sys.sysusers INNER JOIN params ON 1=1
WHERE status > varMinStatus OR name LIKE varType
also via CROSS APPLY
WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
SELECT status, name
FROM sys.sysusers CROSS APPLY params
WHERE status > varMinStatus OR name LIKE varType
Or use a CTE (common table expression) as subselect like:
WITH CTE_Time(Clock)
AS(
SELECT 11 AS [Clock] -- set var
)
SELECT
DATEPART(HOUR, GETDATE()) AS 'actual hour',
CASE
WHEN DATEPART(HOUR, GETDATE()) >= (SELECT [Clock] FROM CTE_Time) THEN 'after'
ELSE 'before'
END AS [Data]
Try put the condition subquery directly inside the the view select statement. you may CAST the XML to VARCHAR(20).
CREATE VIEW [AQB_OB].[GISREQUESTEDBURNS]
AS
SELECT RB.[RequestedBurnsID] AS REQUESTEDBURNID
,BUY.[BurnYear] AS BURNYEAR
,CY.[CurrentYear] AS CURRENTYEAR
,RB.[BurnSitesID] AS BURNSITESID
,[BurnerID] AS BURNERID
,[Contact] AS CONTACT
,[BurnDecision] AS BURNDECISION
,RB.[Comment] AS COMMENT,
(
SELECT DISTINCT BD.[RequestedBurnsID],
[ConditionsReasonsID] = STUFF((SELECT ', ' + CONVERT(VARCHAR (20), [ConditionsReasonsID]) FROM [AQB_OB].[BurnDecisions]
WHERE [RequestedBurnsID]= BD.[RequestedBurnsID] ORDER BY [RequestedBurnsID] ASC
FOR XML PATH ('')) , 1 , 1, '') FROM
[AQB_OB].[BurnDecisions] BD
) AS CONDITIONS
FROM [AQB_MON].[AQB_OB].[RequestedBurns] RB
LEFT join AQB_MON.[AQB_OB].[PileDryness] PD on RB.[PileDrynessID] = PD.[PileDrynessID]
inner join AQB_MON.[AQB_OB].[BurnYear] BUY on BUY.BurnYearID = BP.BurnYearID
inner join AQB_MON.[AQB_OB].[CurrentYear] CY on CY.CurrentYearID = BUY.CurrentYearID

Intersect query with no duplicates

I have not used sql server in a large complex scale in years, and Looking for help on how to proper sintax intersect type query to joing these two data sets, and not create duplicate names. Some patients will have both an order and a clinical event entry and some will only have a clinical event.
Data Set 1
SELECT
distinct
ea.alias as FIN,
per.NAME_Last + ', ' + per.NAME_FIRST + ' ' + Isnull(per.NAME_MIDDLE, '') as PatientName,
oa.action_dt_tm as CirOrder,
od.ORIG_ORDER_DT_TM as DischOrder,
e.disch_dt_tm as ActualDisch,
prs.NAME_FULL_FORMATTED as OrderedBy,
from pathway py
join encounter e on e.CERNER_ENCOUNTER_ID = py.encntr_id
join encntr_alias ea on ea.CERNER_ENCNTR_ID = e.CERNER_ENCOUNTER_ID and ea.ENCNTR_ALIAS_TYPE_WCD = 1049
join person per on per.CERNER_PERSON_ID = e.cerner_PERSON_ID
join orders o on o.CERNER_ENCNTR_ID= e.CERNER_ENCOUNTER_ID and o.CATALOG_wCD = '82111' -- communication order
and o.pathway_catalog_id = '43809296' ---Circumcision Order
join order_action oa on oa.[CERNER_ORDER_ID] = o.CERNER_ORDER_ID and oa.ACTION_TYPE_WCD = '2494'--ordered
join orders od on od.CERNER_ENCNTR_ID= e.CERNER_ENCOUNTER_ID and od.CATALOG_WCD = '203520' --- Discharge Patient
join prsnl prs on prs.CERNER_PERSON_ID = oa.order_provider_id
where py.pathway_catalog_id = '43809296' and ---Circumcision Order
oa.action_dt_tm > '2016-01-01 00:00:00'
and oa.ACTION_DT_TM < '2016-01-19 23:59:59'
--use the report prompts as parameters for the action_dt_tm
Data Set 2
SELECT
distinct e.[CERNER_ENCOUNTER_ID],
ea.alias as FIN,
per.NAME_Last + ', ' + per.NAME_FIRST + ' ' + Isnull(per.NAME_MIDDLE, '') as PatientName,
ce.EVENT_END_DT_TM as CircTime,
od.ORIG_ORDER_DT_TM as DischOrder,
e.disch_dt_tm as ActualDisch,
'' OrderedBy, -- should be blank for this set
cv.DISPLAY
from encounter e
join clinical_event ce on e.CERNER_ENCOUNTER_ID = ce.CERNER_ENCNTR_ID
join encntr_alias ea on ea.CERNER_ENCNTR_ID = e.CERNER_ENCOUNTER_ID and ea.ENCNTR_ALIAS_TYPE_WCD = 1049
join person per on per.CERNER_PERSON_ID = e.cerner_PERSON_ID
join orders od on od.CERNER_ENCNTR_ID= e.CERNER_ENCOUNTER_ID and od.CATALOG_WCD = '203520' --- Discharge Patient
left outer join ENCNTR_LOC_HIST elh on elh.CERNER_ENCNTR_ID = e.CERNER_ENCOUNTER_ID
left outer join CODE_VALUE cv on cv.CODE_VALUE_WK = elh.LOC_NURSE_UNIT_WCD
where ce.event_wcd = '201148' ---Newborn Circumcision
and ce.[RESULT_VAL] = 'Newborn Circumcision'
and ce.EVENT_END_DT_TM > '2016-01-01 00:00:00'
and ce.event_end_dt_tm < '2016-01-19 23:59:59’
and ce.RESULT_STATUS_WCD = '25'
and elh.ACTIVE_STATUS_DT_TM < ce.event_end_dt_tm -- Circ time between the location's active time and end time.
and elh.END_EFFECTIVE_DT_TM > ce.[EVENT_END_DT_TM]
--use the report prompts as parameters for the ce.[EVENT_END_DT_TM]
The structure of an intersect query is as simple as:
select statement 1
intersect
select statement 2
intersect
select statement 3
...
This will return all columns that are in both select statements. The columns returned in the select statements must be of the same quantity and type (or at least be convertible to common type).
You can also do an intersect type of query just using inner joins to filter out records in the one query that are not in the other. So for a simple example let's say you have two tables of colors.
Select distinct ColorTable1.Color
from ColorTable1
join ColorTable2
on ColorTable1.Color = ColorTable2.Color
This will return all the distinct colors in ColorTable1 that are also in ColorTable2. Using joins to filter could help your query perform better, but it does take more thought.
Also see: Set Operators (Transact-SQL)

Resources