SQL Server Group By with Joins - sql

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

Related

How can I put SELECT result set to SELECT column?

I have two tables: Job(ID,Name, etc.) and Address(ID, Job_ID, Name etc). I want to get result like this:
[
{
"Job_ID": 1,
"JobName": "Test",
"Addresses": [
{
"ID": 1,
"Name": "King street"
},
{
"ID": 2,
"Name": "Queen`s street
}
]
}
]
My current query that gets only one address for a job looks like this:
SELECT TOP 100
JO.ID,
JO.Closed as Deleted,
JO.Number as JobNumber,
JO.Name as JobName,
Convert(date, JO.Start_Date) as Start_Date,
JO.Job_Status_ID as Status,
A.ID as Address_ID,
A.Name as Name,
A.Number as Number,
A.Sort_Name as Sort_Name,
A.Address_1 as Address_1,
A.Address_2 as Address_2,
A.ZipCode as ZIP,
A.E_Mail_Address as Email,
A.Web_Site_URL as Web_Site_URL,
A.TAXRATE as Tax_Rate,
A.State
FROM Job JO
INNER JOIN Address A ON A.Job_Id = JO.ID
Is it possible without pivot table(Address_ID, Job_ID)?
You can use FOR JSON to convert you results to JSON. This gives the result you are looking for:
CREATE TABLE #Job (ID INT NOT NULL, Name VARCHAR(50));
INSERT #Job (ID, Name)
VALUES (1, 'Job 1'), (2, 'Job 2');
CREATE TABLE #Address (ID INT NOT NULL, JobID INT NOT NULL, Name VARCHAR(50));
INSERT #Address (ID, JobID, Name)
VALUES (1, 1, 'King street'), (2, 1, 'Queen''s street'), (3, 2, 'Address 3'), (4, 2, 'Address 4');
SELECT JobID = j.ID,
JobName = j.Name,
Addresses = ( SELECT a.ID, a.Name
FROM #Address AS a
WHERE a.JobID = j.ID
FOR JSON AUTO
)
FROM #Job AS j
FOR JSON AUTO;

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

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.

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

Add Subtotal & Total to Pivot

I have the following query
SELECT [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type], ISNULL([2016], 0) AS '2016', ISNULL([2017],0) AS
'2017'
FROM
(
SELECT CUCODE AS 'Acct', CUNAME AS 'Customer', STKCODE AS 'Code', STKNAME AS 'Description', SUM(OD_QTYORD) AS 'Packs Ordered'
, OD_GROSS AS 'Value', CUSORT AS 'Sale Person', LEFT(CUUSER1,3) AS 'Region', DATEPART(yyyy, OD_DATE) AS 'Year', OH_USER2 AS 'Store Type'
FROM STK_STOCK
INNER JOIN ORD_DETAIL ON STK_STOCK.STKCODE=ORD_DETAIL.OD_STOCK_CODE
INNER JOIN ORD_HEADER ON OD_ORDER_NUMBER=OH_ORDER_NUMBER
INNER JOIN SL_ACCOUNTS ON OH_ACCOUNT=CUCODE
WHERE STKCODE IN ('76958', '27225', '27221', '26962', '26959', '26961', '27226', '26963', '26960')
AND OD_QTYORD > 0
AND CUCODE != 'Z9997'
GROUP BY CUCODE, CUNAME, STKCODE, STKNAME, OD_GROSS, CUSORT, CUUSER1, OD_DATE, OH_USER2
) AS SourceTable
PIVOT
(
SUM([Packs Ordered])
FOR [Year] IN ([2016], [2017])
) AS PivotTable;
The output looks great but I want a subtotal for each 'Acct' and a Grand Total for the whole thing.
Can anyone help with this?
You can use group by grouping sets as below:
SELECT [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type], sum([2016]) as [2016], sum([2017]) as [2017] FROM
(
SELECT [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type], ISNULL([2016], 0) AS '2016', ISNULL([2017],0) AS
'2017'
FROM
(
SELECT CUCODE AS 'Acct', CUNAME AS 'Customer', STKCODE AS 'Code', STKNAME AS 'Description', SUM(OD_QTYORD) AS 'Packs Ordered'
, OD_GROSS AS 'Value', CUSORT AS 'Sale Person', LEFT(CUUSER1,3) AS 'Region', DATEPART(yyyy, OD_DATE) AS 'Year', OH_USER2 AS 'Store Type'
FROM STK_STOCK
INNER JOIN ORD_DETAIL ON STK_STOCK.STKCODE=ORD_DETAIL.OD_STOCK_CODE
INNER JOIN ORD_HEADER ON OD_ORDER_NUMBER=OH_ORDER_NUMBER
INNER JOIN SL_ACCOUNTS ON OH_ACCOUNT=CUCODE
WHERE STKCODE IN ('76958', '27225', '27221', '26962', '26959', '26961', '27226', '26963', '26960')
AND OD_QTYORD > 0
AND CUCODE != 'Z9997'
GROUP BY CUCODE, CUNAME, STKCODE, STKNAME, OD_GROSS, CUSORT, CUUSER1, OD_DATE, OH_USER2
) AS SourceTable
PIVOT
(
SUM([Packs Ordered])
FOR [Year] IN ([2016], [2017])
) AS PivotTable
) a
group by GROUPING SETS ( [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type] )
ORDER BY [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type];
Based on Kannan Kandasamy's reply I got this which worked beautifully:
SELECT (CASE
WHEN GROUPING([Acct])=0 AND
GROUPING([Customer]) = 1 AND
GROUPING([Code]) = 1 AND
GROUPING([Description]) = 1 AND
GROUPING([Sale Person]) = 1 AND
GROUPING([Region]) = 1 AND
GROUPING([Store Type]) = 1
THEN 'Total '+ [Acct]
WHEN GROUPING([Acct])=1 AND
GROUPING([Customer]) = 1 AND
GROUPING([Code]) = 1 AND
GROUPING([Description]) = 1 AND
GROUPING([Sale Person]) = 1 AND
GROUPING([Region]) = 1 AND
GROUPING([Store Type]) = 1
THEN 'Total'
ELSE [Acct]
END) AS Acct , ISNULL([Customer],'') AS 'Customer', ISNULL([Code],'') AS 'Code', ISNULL([Description],'') AS 'Description', SUM(ISNULL([Value],'')) AS 'Value', ISNULL([Sale Person],'') AS 'Sales Person',
ISNULL([Region],'') AS 'Region', ISNULL([Store Type],'') AS 'Store Type', SUM([2016]) AS '2016', SUM([2017]) AS '2017'
FROM
(
SELECT [Acct], [Customer], [Code], [Description], [Value], [Sale Person],
[Region], [Store Type], ISNULL([2016], 0) AS '2016', ISNULL([2017],0) AS
'2017'
FROM
(
SELECT CUCODE AS 'Acct', CUNAME AS 'Customer', STKCODE AS 'Code', STKNAME AS 'Description', SUM(OD_QTYORD) AS 'Packs Ordered'
, OD_GROSS AS 'Value', CUSORT AS 'Sale Person', LEFT(CUUSER1,3) AS 'Region', DATEPART(yyyy, OD_DATE) AS 'Year', OH_USER2 AS 'Store Type'
FROM STK_STOCK
INNER JOIN ORD_DETAIL ON STK_STOCK.STKCODE=ORD_DETAIL.OD_STOCK_CODE
INNER JOIN ORD_HEADER ON OD_ORDER_NUMBER=OH_ORDER_NUMBER
INNER JOIN SL_ACCOUNTS ON OH_ACCOUNT=CUCODE
WHERE STKCODE IN ('76958', '27225', '27221', '26962', '26959', '26961', '27226', '26963', '26960')
AND OD_QTYORD > 0
AND CUCODE != 'Z9997'
GROUP BY CUCODE, CUNAME, STKCODE, STKNAME, OD_GROSS, CUSORT, CUUSER1, OD_DATE, OH_USER2
) AS SourceTable
PIVOT
(
SUM([Packs Ordered])
FOR [Year] IN ([2016], [2017])
) AS PivotTable
) a
group by GROUPING SETS (( [Acct], [Customer], [Code], [Description], [Sale Person],
[Region], [Store Type]),([Acct]),());

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