How to GROUP BY an alias - sql-server

I trying to find the amount of classes each of our staff is scheduled to teach, I've counted the amount of times their staffID occurs in the schedule table, and it runs perfect if I only use a staff's first Name but for whatever reason it doesn't work when I try to concatenate their first and last name, and group by the assigned alias. What am I doing wrong?
SELECT DISTINCT sf.StfFirstName + ' ' + sf.StfLastname As StaffName, COUNT(fc.StaffID)
FROM Staff sf
JOIN Faculty_Classes fc
ON sf.StaffID = fc.StaffID
join Classes cl
ON fc.ClassID = cl.ClassID
GROUP BY Sf.StaffName

Just repeat the logic used in the select clause. It may look inefficient but it isn't. Note: Omit the alias given to that logic if pasting into the group by clause.
SELECT sf.StfFirstName + ' ' + sf.StfLastname As StaffName,
COUNT(fc.StaffID)
FROM Staff sf
JOIN Faculty_Classes fc
ON sf.StaffID = fc.StaffID
join Classes cl
ON fc.ClassID = cl.ClassID
GROUP BY sf.StfFirstName + ' ' + sf.StfLastname
;
You can also try without the concatenation, it should also work.
GROUP BY sf.StfFirstName, sf.StfLastname
Aliases created in the select clause are not reusable by the group by clause because the select clause actually gets performed after the group by, in other words the sequence of writing a sql query is not the sequence of operation.

You may repeat the logic as user Used_By_Already suggested or alternatively you can use a common table expression or derived table if you please:
common table expression:
with cte_example -- with name_of_cte as (your query)
as
(
SELECT sf.StfFirstName + ' ' + sf.StfLastname As StaffName, COUNT(fc.StaffID)
FROM Staff sf
JOIN Faculty_Classes fc
ON sf.StaffID = fc.StaffID
join Classes cl
ON fc.ClassID = cl.ClassID
)
select *
from cte_example
group by StaffName
derived table:
select *
from
(
SELECT sf.StfFirstName + ' ' + sf.StfLastname As StaffName, COUNT(fc.StaffID)
FROM Staff sf
JOIN Faculty_Classes fc
ON sf.StaffID = fc.StaffID
join Classes cl
ON fc.ClassID = cl.ClassID
) t1 --note the table alias
group by StaffName

Related

Select where in subquery from one row with CSV values

I'm trying to do a subquery where the value returned is a CSV list of values I want to use for the SELECT WHERE IN clause
SELECT *
FROM Facility.FacilityIO f
where f.FacilityID in (
select Facilities
from FacilityListView
where FacilityID = 'PSY35'
)
FacilityListView looks like this:
FacilityID Facilities
SOL1 SOL1,
PSY35 PSY3,PSY5
SOL1W SOL1,WSR1,
I get 0 results since SQL server is looking for a dataset and not an individual value but I don't know how to tell SQL server to select where f.FacilityID in ('PSY3','PSY5')
Join the tables and use the LIKE operator:
SELECT f.*
FROM Facility.FacilityIO f INNER JOIN FacilityListView v
ON ',' + v.Facilities + ',' LIKE '%,' + f.FacilityID + ',%'
WHERE v.FacilityID = 'PSY35'

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)

Sql Select from another table (loop?)

My SQL skills aren't great hence the post.
I'm trying to get all the contact names based on a company out.
For example I have two statements:
Select Id, CompanyName, Address From Clients
Select ClientId, ContactName From Contacts
You may have many contacts to a single client
Result: (I need all the contact names in a single column)
ContactName Company Address
----------------------------------------
Johh, Steve 123 Comp 12345 Address
David,Mike, Sarah 44 Comp 111 Address
A working example would be very much appreciated.
SELECT DISTINCT (
SELECT ISNULL(ct.ContactName, '') + ', '
FROM dbo.Clients cl JOIN dbo.Contacts ct ON cl.Id = ct.ClientId
WHERE cl.ID = cl2.Id
FOR XML PATH('')) AS ContactName, CAST(cl2.Id AS nvarchar(7)) + ' ' + cl2.CompanyName AS Company, Address
FROM dbo.Clients cl2
ORDER BY 2
Demo on SQLFiddle
Firstly build all the Contact Names for a Company into a Single Column. Assuming the database to be SQL Server, I'm using a Common Table Expression to store the single column contact list. Once the CTE is built, join it with the Clients table to get the ContactNames. FOR XML is used to concatenate rows.
WITH CTEContactList(ClientID,ContactNames)
AS
(
SELECT c1.ClientID,
Names = SUBSTRING(( SELECT ', ' + c2.ContactName
FROM Contacts c2
WHERE c1.ClientID = c2.ClientID
FOR XML PATH ('')),3,8000 ))
FROM Contacts c1
GROUP BY c1.ClientID
)
SELECT
cl.ID,
cl.CompanyName,
cl.Address,
ctelist.ContactNames
FROM Clients cl
INNER JOIN CTEContactList ctelist
ON cl.ID = cteList.ClientID
Sounds like you need to do a table join.
Example: two tables here
1. Person
2. Orders
Query:
SELECT
Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders ON Persons.P_Id = Orders.P_Id
ORDER BY Persons.LastName
You didn't specify your DBMS, so I'm assuming PostgreSQL:
select string_agg(ct.contactName, ', '), cl.companyname, cl.address
from contacts ct
join clients cl on cl.id = ct.clientId
group by cl.companyname, cl.address

Resources