How do you only return one field when there are multiple entries for each field? - sql

I am trying to only return one email address for each employee. An Employee can be both an employee and a student. If you have both an employee and student email address then I only want to return the employee email address else if you only have student email address then return the student email address.
Here is the entire query:
select --spriden_pidm as pidm,
spriden_id as ban_id,
spriden_last_name as lastname,
spriden_first_name as firstname,
gmal.email,
phone_number.area || phone_number.phone as phone_number,
addr.permanent_address AS street,
addr.permanent_city AS city,
addr.permanent_state AS state,
addr.permanent_zip AS zip,
case
when nbrjobs_ecls_code in ('E1', 'E2', 'EN', 'F1', 'F2') and nbrjobs_ann_salary between 0 and 49999.99 then 'EHRA1'
when nbrjobs_ecls_code in ('E1', 'E2', 'EN', 'F1', 'F2') and nbrjobs_ann_salary between 50000 and 99999.99 then 'EHRA2'
when nbrjobs_ecls_code in ('E1', 'E2', 'EN', 'F1', 'F2') and nbrjobs_ann_salary between 100000 and 149999.99 then 'EHRA3'
when nbrjobs_ecls_code in ('E1', 'E2', 'EN', 'F1', 'F2') and nbrjobs_ann_salary >= 150000 then 'EHRA4'
when nbrjobs_ecls_code in ('SE', 'SN', 'LE') and nbrjobs_ann_salary between 0 and 49999.99 then 'SHRA1'
when nbrjobs_ecls_code in ('SE', 'SN', 'LE') and nbrjobs_ann_salary between 50000 and 99999.99 then 'SHRA2'
when nbrjobs_ecls_code in ('SE', 'SN', 'LE') and nbrjobs_ann_salary between 100000 and 149999.99 then 'SHRA3'
when nbrjobs_ecls_code in ('SE', 'SN', 'LE') and nbrjobs_ann_salary >= 150000 then 'SHRA4'
when nbrjobs_ecls_code in ('FA') then 'AF'
when nbrjobs_ecls_code in ('SH', 'SS', 'TS', 'WS') then 'M1'
else
null
end as empl_cat
from nbrjobs a,
spriden,
(select goremal_pidm as pidm,
goremal_email_address as email
from goremal
where goremal_emal_code in ('EMPL', 'STDN')
and goremal_status_ind = 'A') gmal,
(SELECT sprtele_pidm AS pidm,
sprtele_phone_area AS area,
sprtele_phone_number AS phone
FROM sprtele c
WHERE sprtele_tele_code = 'CA'
AND sprtele_primary_ind = 'Y'
AND sprtele_status_ind IS NULL
AND sprtele_seqno =
(SELECT MAX (sprtele_seqno)
FROM sprtele
WHERE sprtele_tele_code = 'CA'
AND sprtele_primary_ind = 'Y'
AND sprtele_status_ind IS NULL
AND sprtele_pidm = c.sprtele_pidm)) phone_number,
--spraddr
(SELECT spraddr_pidm AS pidm,
spraddr_street_line1 AS permanent_address,
spraddr_city AS permanent_city,
spraddr_stat_code AS permanent_state,
spraddr_zip AS permanent_zip
FROM spraddr b
WHERE spraddr_atyp_code = 'CA'
AND spraddr_status_ind IS NULL
AND spraddr_seqno =
(SELECT MAX (spraddr_seqno)
FROM spraddr
WHERE spraddr_atyp_code = 'CA'
AND spraddr_status_ind IS NULL
AND spraddr_pidm = b.spraddr_pidm)) addr
where a.nbrjobs_pidm = spriden_pidm
and a.nbrjobs_pidm = gmal.pidm(+)
and a.nbrjobs_pidm = phone_number.pidm(+)
and a.nbrjobs_pidm = addr.pidm(+)
and spriden_change_ind is null
and a.nbrjobs_sgrp_code = to_char(sysdate, 'YYYY')
and a.nbrjobs_effective_date = (select max(b.nbrjobs_effective_date)
from nbrjobs b
where b.nbrjobs_pidm = a.nbrjobs_pidm
and b.nbrjobs_posn = a.nbrjobs_posn
and b.nbrjobs_effective_date <= sysdate
--and b.nbrjobs_ecls_code in ('E1','E2','EN','F1','F2','SE','SN','LE')
and b.nbrjobs_ecls_code in ('E1','E2','EN','F1','F2','SE','SN','LE', 'RF', 'AF', 'FA', 'SH', 'SS', 'TS', 'WS')
and b.nbrjobs_sgrp_code = to_char(sysdate, 'YYYY'))
and a.nbrjobs_status <> 'T';`
and this is the part of the query I am trying to change to return the desired email address
(select goremal_pidm as pidm,
goremal_email_address as email
from goremal
where goremal_emal_code in ('EMPL', 'STDN')
and goremal_status_ind = 'A') gmal,

So the issue is that the query will return two email addresses if the employee is also a student? What you can do in this case is PIVOT the data, then use COALESCE() to get the student email where the employee email is NULL. The below query would replace the problematic subquery:
SELECT pidm, COALESCE(empl_email, stdn_email) AS email
FROM (
SELECT goremal_pidm AS pidm, goremal_email_address AS email, goremal_emal_code
FROM goremal
WHERE goremal_emal_code in ('EMPL', 'STDN')
AND goremal_status_ind = 'A'
) PIVOT (
MAX(email) FOR goremal_emal_code IN ('EMPL' AS empl_email, 'STDN' AS stdn_email)
)
EDIT: As an aside, you can use conditional aggregation instead of an explicit PIVOT (helpful if you're using Oracle 9i or lower):
SELECT pidm, COALESCE(empl_email, stdn_email) AS email FROM (
SELECT goremal_pidm AS pidm
, MAX(CASE WHEN goremal_emal_code = 'EMPL' THEN goremal_email_address END) AS empl_email
, MAX(CASE WHEN goremal_emal_code = 'STDN' THEN goremal_email_address END) AS stdn_email
FROM goremal
WHERE goremal_emal_code in ('EMPL', 'STDN')
AND goremal_status_ind = 'A'
GROUP BY goremal_pidm
)
Hope this helps.

Try using NVL2, as a example for your case -
NVL2(EMP_EMAIL_ADR, EMP_EMAIL_ADR, STDN_EMAIL_ADR)
This clause will return if the Employee email address is not null else it returns Student email address.
Hope this helps.

Related

selecting random rows from table

I have the following query, returning over 100 000 rows, How do I select random 8000 rows from(for example) vw_client_uli_member_type? Can someone provide an example on my query?
SELECT ind_cst_key,
ind_int_code as 'Individual Type',
ind_first_name as 'First Name',
ind_last_name as 'Last Name',
cst_recno as 'Member ID',
cst_eml_address_dn as 'Email Address',
adr_city as 'City',
adr_state as 'State' ,
adr_country as 'Country',
cst_org_name_dn as 'Company',
cst_ixo_title_dn as 'Job Title',
mem_member_type as 'Member Type'
FROM
co_individual WITH (NOLOCK)
JOIN co_individual_ext WITH (NOLOCK) ON ind_cst_key_ext=ind_cst_key
JOIN co_customer WITH (NOLOCK) ON cst_key=ind_cst_key and ind_delete_flag=0
and ind_deceased_flag=0
LEFT JOIN co_customer_x_address WITH (NOLOCK) ON cst_cxa_key=cxa_key
LEFT JOIN co_address WITH (NOLOCK) ON adr_key=cxa_adr_key
LEFT JOIN vw_client_uli_member_type WITH (NOLOCK) ON cst_key=mem_cst_key
WHERE mem_member_type Is Null AND adr_country = N'UNITED STATES' AND ind_deceased_flag != 1 AND ind_key_leader_flag_ext != 1 AND ind_int_code != N'Staff' AND ind_int_code != N'Spouse' AND ind_int_code != N'Press'
ORDER BY adr_country DESC
You can just add to yours query:
SELECT TOP 8000 (columns) FROM table
ORDER BY NEWID()
That should work.
This is what your code looks like after #brunofernandes suggested
SELECT top 8000 ind_cst_key,
ind_int_code as 'Individual Type',
ind_first_name as 'First Name',
ind_last_name as 'Last Name',
cst_recno as 'Member ID',
cst_eml_address_dn as 'Email Address',
adr_city as 'City',
adr_state as 'State' ,
adr_country as 'Country',
cst_org_name_dn as 'Company',
cst_ixo_title_dn as 'Job Title',
mem_member_type as 'Member Type'
FROM
co_individual WITH (NOLOCK)
JOIN co_individual_ext WITH (NOLOCK) ON ind_cst_key_ext=ind_cst_key
JOIN co_customer WITH (NOLOCK) ON cst_key=ind_cst_key and ind_delete_flag=0
and ind_deceased_flag=0
LEFT JOIN co_customer_x_address WITH (NOLOCK) ON cst_cxa_key=cxa_key
LEFT JOIN co_address WITH (NOLOCK) ON adr_key=cxa_adr_key
LEFT JOIN vw_client_uli_member_type WITH (NOLOCK) ON cst_key=mem_cst_key
WHERE mem_member_type Is Null AND adr_country = N'UNITED STATES' AND ind_deceased_flag != 1 AND ind_key_leader_flag_ext != 1 AND ind_int_code != N'Staff' AND ind_int_code != N'Spouse' AND ind_int_code != N'Press'
ORDER BY NEWID(), adr_country DESC

SQL Server Group By with Joins

SELECT
[CustomerKey] AS 'Cust #',
CU.[CompanyName] AS 'Company Name',
ISS.InvoiceDate AS 'Invoice Date',
ISS.InvoiceTotal AS 'Invoice Total',
ISNULL(CU.ShopPhone,'') AS 'Company Shop',
ISNULL(CU.CellPhone,'') AS 'Company Cell',
ISNULL(CU.OfficePhone,'') AS 'Company Office',
ISNULL(CF.FirstName, '') AS 'FName',
ISNULL(CF.LastName,'') AS 'LName',
ISNULL(CF.WorkPhone,'') AS 'Contact Work',
ISNULL(CF.CellPhone,'') AS 'Contact Cell',
ISNULL(CF.HomePhone,'') AS 'Contact Home',
ISNULL(CF.EMail,'') AS 'Contact Email',
PSO.OutsidePartsSalespersonName
FROM
[ProfitMaster].[dbo].[vwAC_SSR_Customer] CU with (nolock)
LEFT JOIN
[ProfitMaster].[dbo].[vwAC_SSR_InvoiceSalesSummary] ISS with (nolock) ON CU.CustomerKey = ISS.Customer
JOIN
[ProfitMaster].[dbo].[vwSV_INV_PartsSalesOrder] PSO with (nolock) ON PSO.PartsSalesOrderInvoiceID = ISS.PartsSalesOrderInvoiceID
LEFT JOIN
(SELECT
EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail
FROM
[ProfitMaster].[dbo].[vwGB_CON_ContactFull] with (nolock)
WHERE
EntityID IS NOT NULL
AND FirstName <> ''
AND EntityTypeID = '3'
AND SetDefault = '1'
GROUP BY
EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail) AS CF ON CU.CustomerID = CF.EntityID
WHERE
CU.Inactive = '0'
AND ISS.InvoiceType = 'Parts Order'
AND ISS.InvoiceDate BETWEEN '2017-02-01 00:00:00.000' AND '2017-03-31 3:59:59.000'
AND CU.CustomerBaseBranchID = '1'
AND PSO.OutsidePartsSalespersonName IN ('Dave Freeland', 'Mark Miller', 'Ryan Oaks')
GROUP BY
CU.CustomerKey, CU.[CompanyName],
ISS.InvoiceDate, ISS.InvoiceTotal,
CU.ShopPhone, CU.CellPhone, CU.OfficePhone,
CF.FirstName, CF.LastName, CF.WorkPhone, CF.CellPhone,
CF.HomePhone, CF.EMail, PSO.OutsidePartsSalespersonName
ORDER BY
CU.CompanyName, ISS.InvoiceDate
How can I group this to SUM ISS.InvoiceTotal grouped by CustomerKey?
I keep getting the "is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause." error.
Any ideas?
If you SUM() in the ISS table you can't select from it or add it to the GROUP BY.
SELECT
[CustomerKey] AS 'Cust #',
CU.[CompanyName] AS 'Company Name',
LAST(ISS.InvoiceDate) AS 'Invoice Date',
SUM(ISS.InvoiceTotal) AS 'Invoice Total',
ISNULL(CU.ShopPhone,'') AS 'Company Shop',
ISNULL(CU.CellPhone,'') AS 'Company Cell',
ISNULL(CU.OfficePhone,'') AS 'Company Office',
ISNULL(CF.FirstName, '') AS 'FName',
ISNULL(CF.LastName,'') AS 'LName',
ISNULL(CF.WorkPhone,'') AS 'Contact Work',
ISNULL(CF.CellPhone,'') AS 'Contact Cell',
ISNULL(CF.HomePhone,'') AS 'Contact Home',
ISNULL(CF.EMail,'') AS 'Contact Email',
PSO.OutsidePartsSalespersonName
FROM
[ProfitMaster].[dbo].[vwAC_SSR_Customer] CU with (nolock)
LEFT JOIN
[ProfitMaster].[dbo].[vwAC_SSR_InvoiceSalesSummary] ISS with (nolock) ON CU.CustomerKey = ISS.Customer
JOIN
[ProfitMaster].[dbo].[vwSV_INV_PartsSalesOrder] PSO with (nolock) ON PSO.PartsSalesOrderInvoiceID = ISS.PartsSalesOrderInvoiceID
LEFT JOIN
(SELECT
EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail
FROM
[ProfitMaster].[dbo].[vwGB_CON_ContactFull] with (nolock)
WHERE
EntityID IS NOT NULL
AND FirstName <> ''
AND EntityTypeID = '3'
AND SetDefault = '1'
GROUP BY
EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail) AS CF ON CU.CustomerID = CF.EntityID
WHERE
CU.Inactive = '0'
AND ISS.InvoiceType = 'Parts Order'
AND ISS.InvoiceDate BETWEEN '2017-02-01 00:00:00.000' AND '2017-03-31 3:59:59.000'
AND CU.CustomerBaseBranchID = '1'
AND PSO.OutsidePartsSalespersonName IN ('Dave Freeland', 'Mark Miller', 'Ryan Oaks')
GROUP BY
CU.CustomerKey, CU.[CompanyName],
CU.ShopPhone, CU.CellPhone, CU.OfficePhone,
CF.FirstName, CF.LastName, CF.WorkPhone, CF.CellPhone,
CF.HomePhone, CF.EMail, PSO.OutsidePartsSalespersonName
ORDER BY
CU.CompanyName

SQL: Build dynamic query from list of tables received from user

I am attempting to build a dynamic query based on a list of tables as received from a user.
I have a couple attempted solutions below.
I think the CTE is the way to go but am having difficulty figuring out how to make it happen.
I would really appreciate whatever genius can let me know how to do this!
these are the tables:
W, WD, WE, WSF, WSFE, XDF, XDFE, Y, YD, Z, ZD
these are the columns to join by for each group of tables:
W, Y, WD, WE, WSF
WID
WSF, WSFE, XDF
WSFID
XDF, XDFE
XDFID
Y, YD, Z
YID
Z, ZD
ZID
if the user selects W, Y, Z then build this query (which could then be executed by exec or sp_executesql):
select * from #W w join #Y y on y.WID = w.WID join #Z z on z.YID = y.YID
declare #Fields table (
ID int identity not NULL,
Name varchar(200)
)
declare #Tables table (
ID int identity not NULL,
Field varchar(200),
TempTable varchar(200)
)
declare #QueryTables table (
ID int identity not NULL,
[Table] varchar(200),
Alias varchar(20)
)
declare #QueryJoins table (
ID int identity not NULL,
Table1 varchar(20),
Col1 varchar(200),
Table2 varchar(20),
Col2 varchar(200)
)
insert #Fields
values
('W'),
('Y'),
('Z')
insert #Tables
values
('W', '#W'),
('WD', '#WD'),
('WE', '#WE'),
('WSF', '#WSF'),
('WSFE', '#WSFE'),
('XDF', '#XDF'),
('XDFE', '#XDFE'),
('Y', '#Y'),
('YD', '#YD'),
('Z', '#Z'),
('ZD', '#ZD')
insert #QueryTables
values
('#W', 'w'),
('#WD', 'wd'),
('#WE', 'we'),
('#WSF', 'wsf'),
('#WSFE', 'wsfe'),
('#XDF', 'xdf'),
('#XDFE', 'xdfe'),
('#Y', 'y'),
('#YD', 'yd'),
('#Z', 'z'),
('#ZD', 'zd')
insert #QueryJoins
values
('w', 'WID', 'wd', 'WID'),
('w', 'WID', 'we', 'WID'),
('w', 'WID', 'wsf', 'WID'),
('w', 'WID', 'xdf', 'WID'),
('w', 'WID', 'y', 'WID'),
('wd', 'WID', 'w', 'WID'),
('we', 'WID', 'wd', 'WID'),
('wsf', 'WID', 'wd', 'WID'),
('wsf', 'WSFID', 'wsfe', 'WSFID'),
('wsfe', 'WSFID', 'wsf', 'WSFID'),
('wsf', 'WSFID', 'xdf', 'WSFID'),
('xdf', 'WID', 'w', 'WID'),
('xdf', 'WSFID', 'wsf', 'WSFID'),
('xdf', 'XDFID', 'xdfe', 'XDFID'),
('xdfe', 'XDFID', 'xdf', 'XDFID'),
('y', 'WID', 'w', 'WID'),
('y', 'YID', 'yd', 'YID'),
('yd', 'YID', 'y', 'YID'),
('y', 'YID', 'z', 'YID'),
('z', 'YID', 'y', 'YID'),
('z', 'ZID', 'zd', 'ZID'),
('zd', 'ZID', 'z', 'ZID')
--attempted solution number 1:
select
*
from #Fields vf
join #Tables vt
on vt.Field = vf.Name
join #QueryTables vqt
on vqt.[Table] = vt.TempTable
join #QueryJoins vqj
on vqj.Table1 = vqt.Alias
join #QueryTables vqt2
on vqt2.Alias = vqj.Table2
join #Tables vt2
on vt2.TempTable = vqt2.[Table]
join #Fields vf2
on vf2.Name = vt2.Field
--attempted solution number 2:
;with cte (FieldID, [Table], Table1, Col1, Table2, Col2, I) as (
select
vf.ID as FieldID,
vqt.[Table],
vqj.Table1,
vqj.Col1,
vqj.Table2,
vqj.Col2,
1
from #Fields vf
join #Tables vt
on vt.Field = vf.Name
join #QueryTables vqt
on vqt.[Table] = vt.TempTable
join #QueryJoins vqj
on vqj.Table1 = vqt.Alias
union all
select
vf.ID as FieldID,
vqt.[Table],
vqj.Table1,
vqj.Col1,
vqj.Table2,
vqj.Col2,
I + 1
from #Fields vf
join #Tables vt
on vt.Field = vf.Name
join #QueryTables vqt
on vqt.[Table] = vt.TempTable
join #QueryJoins vqj
on vqj.Table1 = vqt.Alias
join cte cte
on cte.Table1 = vqj.Table2
and cte.Table2 = vqj.Table1
where I <= FieldID --a feeble attempt to control the recursion
)
select * from cte
An interesting problem, definitely a data modeling code smell (if Z, Y, and YD all have a YID column, sounds like you need a bridge table or similar construct to manage the relationships there. Or if Z and YD are small lookups, just join them all and let the optimizer handle the overhead.)
Note: I made the fields self join on Name < Name, so you only need the QueryJoins data where Table1 < Table2. This would cut your QueryJoins table in half, but you're also missing some of the "correct" joins (ie you have we/wd but not wd/we)
declare #Fields table (
ID int identity not NULL,
Name varchar(200)
)
declare #Tables table (
ID int identity not NULL,
Field varchar(200),
TempTable varchar(200)
)
declare #QueryTables table (
ID int identity not NULL,
[Table] varchar(200),
Alias varchar(20)
)
declare #QueryJoins table (
ID int identity not NULL,
Table1 varchar(20),
Col1 varchar(200),
Table2 varchar(20),
Col2 varchar(200)
)
insert #Fields
values
('W'),
('Y'),
('Z')
insert #Tables
values
('W', '#W'),
('WD', '#WD'),
('WE', '#WE'),
('WSF', '#WSF'),
('WSFE', '#WSFE'),
('XDF', '#XDF'),
('XDFE', '#XDFE'),
('Y', '#Y'),
('YD', '#YD'),
('Z', '#Z'),
('ZD', '#ZD')
insert #QueryTables
values
('#W', 'w'),
('#WD', 'wd'),
('#WE', 'we'),
('#WSF', 'wsf'),
('#WSFE', 'wsfe'),
('#XDF', 'xdf'),
('#XDFE', 'xdfe'),
('#Y', 'y'),
('#YD', 'yd'),
('#Z', 'z'),
('#ZD', 'zd')
insert #QueryJoins
values
('w', 'WID', 'wd', 'WID'),
('w', 'WID', 'we', 'WID'),
('w', 'WID', 'wsf', 'WID'),
('w', 'WID', 'xdf', 'WID'),
('w', 'WID', 'y', 'WID'),
('wd', 'WID', 'w', 'WID'),
('we', 'WID', 'wd', 'WID'),
('wsf', 'WID', 'wd', 'WID'),
('wsf', 'WSFID', 'wsfe', 'WSFID'),
('wsfe', 'WSFID', 'wsf', 'WSFID'),
('wsf', 'WSFID', 'xdf', 'WSFID'),
('xdf', 'WID', 'w', 'WID'),
('xdf', 'WSFID', 'wsf', 'WSFID'),
('xdf', 'XDFID', 'xdfe', 'XDFID'),
('xdfe', 'XDFID', 'xdf', 'XDFID'),
('y', 'YID', 'yd', 'YID'),
('yd', 'YID', 'y', 'YID'),
('y', 'YID', 'z', 'YID'),
('z', 'ZID', 'zd', 'ZID'),
('zd', 'ZID', 'z', 'ZID')
;
with a as (
select
row_number() over (order by Name) as rn, Name, Field, TempTable, [Table], Alias
from #Fields vf
join #Tables vt
on vt.Field = vf.Name
join #QueryTables vqt
on vqt.[Table] = vt.TempTable )
select 'select * from ' + stuff((
select
concat(
case when a.rn =1 then a.TempTable else '' end,
' ',
case when a.rn =1 then a.Alias else '' end,
' join ',
a2.TempTable,
' ' ,
a2.alias,
' on ',
q.Table1,
'.',
q.Col1,
' = ',
q.Table2 ,
'.',
q.Col2 ) from a
left join a a2
on a.name < a2.name
inner join #QueryJoins q
on q.Table1 = a.alias
and q.Table2 = a2.alias
for xml path('')), 1, 1, '')

How to replace the IN operator with EXISTS operator, for the where clause part of the query?

WHERE (
((SERVICECOMPONENT_ID IN (123, 150, 198, 199, 290, 287, 291, 289, 288, 286, 282, 281)))
OR ((SERVICEREQUEST_ID IN (
SELECT distinct(SR.SERVICEREQUEST_ID)
FROM SERVICE_REQUEST SR,ASSIGNED_SR_PROJECTS ASP,PROJECT_RESOURCES PRS
WHERE SR.SERVICEREQUEST_ID = ASP.SERVICEREQUEST_ID
AND PRS.PROJECT_ID = ASP.PROJECT_ID
AND PRS.RESPONSIBILITY IN ('MANAGER','LEAD')
AND PRS.RESOURCE_ID =180 )) )
)
In general,
SELECT a FROM b WHERE c IN (SELECT d FROM e)
is equivalent to
SELECT a FROM b WHERE EXISTS (SELECT 1 FROM e WHERE c = d)
The SERVICEREQUEST_ID IN (subquery) part of your code example translates to:
OR EXISTS (
SELECT 1
FROM
SERVICE_REQUEST SR,
ASSIGNED_SR_PROJECTS ASP,
PROJECT_RESOURCES PRS
WHERE
SR.SERVICEREQUEST_ID = ASP.SERVICEREQUEST_ID
AND PRS.PROJECT_ID = ASP.PROJECT_ID
AND PRS.RESPONSIBILITY IN ('MANAGER', 'LEAD')
AND PRS.RESOURCE_ID = 180
AND mytable.SERVICEREQUEST_ID = SR.SERVICEREQUEST_ID
)
if you have static list of elements It's better to use "IN".... If you have a subquery and it is returning more than one value then Use Exist...
There is no Difference in Both clauses..
WHERE (
( (SERVICECOMPONENT_ID IN ( 123 , 150 , 198 , 199 , 290 , 287 , 291 , 289 , 288 , 286 , 282 , 281 )) )
OR ( (SERVICEREQUEST_ID IN ( 1952 , 2387 , 3618 , 3633 , 4178 , 4432 , 5090 , 5271 , 6068 , 6320 , 6396 , 6526 , 7162 , 7442 , 7558 , 7639 , 7688 , 8176 , 8189 , 8338 , 8460 , 8461 , 8598 , 8612 , 8628 , 8675 , 8775 , 8869 , 8886 , 8898 )) )
OR ( (REQUESTED_BY LIKE 'XXXXXXX#example.com' ) )
OR ( ( EXISTS ( SELECT count(distinct(SR.SERVICEREQUEST_ID)) FROM SERVICE_REQUEST SR,ASSIGNED_SR_PROJECTS ASP,PROJECT_RESOURCES PRS WHERE SR.SERVICEREQUEST_ID = ASP.SERVICEREQUEST_ID AND PRS.PROJECT_ID = ASP.PROJECT_ID AND PRS.RESPONSIBILITY IN ('MANAGER','LEAD') AND PRS.RESOURCE_ID =180 )) )
OR ( (STATUS_CODE LIKE 'OPEN' ) AND ( EXISTS (SELECT count(COMPONENT.CATEGORY_ID) FROM PROJECTMASTER PROJECTS, BUDGET BUDGET, CONTRACT CONTRACT,COMPONENTS COMPONENT, PROJECT_RESOURCES PROJ_RESOURCES, CATEGORY_OWNER_ASSIGNMENT CATEGORYOWNER, SERVICECATEGORYASSIGNMENT CATEGORYASSIGNMENT WHERE PROJECTS.PROJECT_ID = PROJ_RESOURCES.PROJECT_ID AND PROJECTS.BUDGET_ID = BUDGET.BUDGET_ID AND BUDGET.CONTRACT = CONTRACT.CONTRACT_ID AND CATEGORYASSIGNMENT.CONTRACT_ID = CONTRACT.CONTRACT_ID AND COMPONENT.COMPONENT_ID = CATEGORYASSIGNMENT.COMPONENT_ID AND CATEGORYOWNER.CATEGORY_ID = COMPONENT.CATEGORY_ID AND CATEGORYOWNER.USER_ID = PROJ_RESOURCES.RESOURCE_ID AND (CATEGORYOWNER.OWNER_FLAG = 'Y' OR CATEGORYOWNER.MEMBER_FLAG = 'Y') AND PROJ_RESOURCES.RESOURCE_ID = 180 AND PROJ_RESOURCES.ACTIVE_FLAG = 'Y' AND CATEGORYASSIGNMENT.ACTIVE_FLAG = 'Y' AND PROJ_RESOURCES.RESPONSIBILITY IN ('MANAGER', 'LEAD') )) )
)
read this for further clarification..
Difference between EXISTS and IN in SQL?

Select from select with case statement and union all

When I am executing query
SELECT Settlement_Fees.Participant_Name, Settlement_Fees.Account, Settlement_Fees.Billing_Account, Settlement_Fees.Descr1, Settlement_Fees.Market, Settlement_Fees.Instrum
--, IIf(Settlement_Fees.Instr_Type='Internal','bsinternal',Settlement_Fees.Instr_Type) AS Expr1
,(case when Settlement_Fees.Instr_Type='Internal' then 'bsinternal'
else Settlement_Fees.Instr_Type
end )
, Settlement_Fees.Country, Settlement_Fees.Nr_Instr_Business_Unit, Settlement_Fees.Nr_Instr_Account, Settlement_Fees.Avg_EUR_Rate, Settlement_Fees.Fee_Amount_EUR, Settlement_Fees.Value_Date_Adj
FROM Settlement_Fees)
union all
(select '','',Billing_Account,'','','',
( case when Instr_Type like '%Bridge%' or Instr_Type = '%Internal%' then 'Bszridge/Internal'
else Instr_Type
end )
,'','',Nr_Instr_Account ,'',Fee_Amount_EUR ,''
from Settlement_Fees group by Settlement_Fees.Billing_Account,Settlement_Fees.Instr_Type
,Settlement_Fees.Nr_Instr_Account,Fee_Amount_EUR)
union all
(select '','',Billing_Account,'','','','Total','','',sum(Nr_Instr_Account),'',sum(Fee_Amount_EUR) ,''
from Settlement_Fees group by Billing_Account
Its is working fine
but when i am executin with select * from () its giving me error "Msg 102, Level 15, State 1, Line 33
Incorrect syntax near ')'." for the following query
SELECT *
FROM ((SELECT settlement_fees.participant_name,
settlement_fees.ACCOUNT,
settlement_fees.billing_account,
settlement_fees.descr1,
settlement_fees.market,
settlement_fees.instrum
--, IIf(Settlement_Fees.Instr_Type='Internal','bsinternal',Settlement_Fees.Instr_Type) AS Expr1
,
( CASE
WHEN settlement_fees.instr_type = 'Internal' THEN
'bsinternal'
ELSE settlement_fees.instr_type
END ),
settlement_fees.country,
settlement_fees.nr_instr_business_unit,
settlement_fees.nr_instr_account,
settlement_fees.avg_eur_rate,
settlement_fees.fee_amount_eur,
settlement_fees.value_date_adj
FROM settlement_fees)
UNION ALL
(SELECT '',
'',
billing_account,
'',
'',
'',
( CASE
WHEN instr_type LIKE '%Bridge%'
OR instr_type = '%Internal%' THEN 'Bszridge/Internal'
ELSE instr_type
END ),
'',
'',
nr_instr_account,
'',
fee_amount_eur,
''
FROM settlement_fees
GROUP BY settlement_fees.billing_account,
settlement_fees.instr_type,
settlement_fees.nr_instr_account,
fee_amount_eur)
UNION ALL
(SELECT '',
'',
billing_account,
'',
'',
'',
'Total',
'',
'',
SUM(nr_instr_account),
'',
SUM(fee_amount_eur),
''
FROM settlement_fees
GROUP BY billing_account))
You shoud name your subquery:
Select * from () subqueryName
select * from(
(SELECT Settlement_Fees.Participant_Name, Settlement_Fees.Account, Settlement_Fees.Billing_Account, Settlement_Fees.Descr1, Settlement_Fees.Market, Settlement_Fees.Instrum
--, IIf(Settlement_Fees.Instr_Type='Internal','bsinternal',Settlement_Fees.Instr_Type) AS Expr1
,(case when Settlement_Fees.Instr_Type='Internal' then 'bsinternal'
else Settlement_Fees.Instr_Type
end )
, Settlement_Fees.Country, Settlement_Fees.Nr_Instr_Business_Unit, Settlement_Fees.Nr_Instr_Account, Settlement_Fees.Avg_EUR_Rate, Settlement_Fees.Fee_Amount_EUR, Settlement_Fees.Value_Date_Adj
FROM Settlement_Fees)
union all
(select '','',Billing_Account,'','','',
( case when Instr_Type like '%Bridge%' or Instr_Type = '%Internal%' then 'Bszridge/Internal'
else Instr_Type
end )
,'','',Nr_Instr_Account ,'',Fee_Amount_EUR ,''
from Settlement_Fees group by Settlement_Fees.Billing_Account,Settlement_Fees.Instr_Type
,Settlement_Fees.Nr_Instr_Account,Fee_Amount_EUR)
union all
(select '','',Billing_Account,'','','','Total','','',sum(Nr_Instr_Account),'',sum(Fee_Amount_EUR) ,''
from Settlement_Fees group by Billing_Account
)) subqueryName
You need to give a table alias to the derived table. e.g. add as t to the very end of the query.
Additionally to fix the issue raised in the comments change
( CASE
WHEN settlement_fees.instr_type = 'Internal' THEN
'bsinternal'
ELSE settlement_fees.instr_type
END )
to
CASE
WHEN settlement_fees.instr_type = 'Internal' THEN
'bsinternal'
ELSE settlement_fees.instr_type
END AS Foo
You need to give your derived table a name. Doesn't matter what. For example:
SELECT
...
FROM
(...derived table) myDerivedTableName
You have an extra set of () and aliasing your inline view/derived table also helps e.g.
select * from(
SELECT
Settlement_Fees.Participant_Name,
Settlement_Fees.Account,
Settlement_Fees.Billing_Account,
Settlement_Fees.Descr1,
Settlement_Fees.Market,
Settlement_Fees.Instrum,
(case when Settlement_Fees.Instr_Type='Internal' then 'bsinternal'
else Settlement_Fees.Instr_Type
end ) as SomthingHere,
Settlement_Fees.Country,
Settlement_Fees.Nr_Instr_Business_Unit,
Settlement_Fees.Nr_Instr_Account,
Settlement_Fees.Avg_EUR_Rate,
Settlement_Fees.Fee_Amount_EUR,
Settlement_Fees.Value_Date_Adj
FROM Settlement_Fees
UNION ALL select
'',
'',
Billing_Account,
'',
'',
'',
( case when Instr_Type like '%Bridge%' or Instr_Type = '%Internal%' then 'Bszridge/Internal'
else Instr_Type
end ),
'',
'',
Nr_Instr_Account ,
'',
Fee_Amount_EUR ,
''
from
Settlement_Fees
group by
Settlement_Fees.Billing_Account,
Settlement_Fees.Instr_Type,
Settlement_Fees.Nr_Instr_Account,
Fee_Amount_EUR
union all select
'',
'',
Billing_Account,
'',
'',
'',
'Total',
'',
'',
sum(Nr_Instr_Account),
'',
sum(Fee_Amount_EUR) ,
''
from
Settlement_Fees
group by
Billing_Account
) as foo