Returning the sum of a select statement SQL - sql

I have created a SELECT statement:
SELECT ARII2.Amount
FROM
AR_Customer ARC2
Inner JOIN AR_Customer_Site ARCS2 On ARC2.Customer_Id = ARCS2.Customer_Id AND ARCS2.Customer_Id = ARC2.Customer_Id
INNER JOIN AR_Customer_System ARCSYS2 On ARCS2.Customer_Site_Id = ARCSYS2.Customer_Site_Id
INNER JOIN AR_Branch ARB2 ON ARB2.Branch_Id = ARC2.Branch_Id
INNER JOIN AR_Invoice ARIN2 ON ARIN2.Customer_Site_Id = ARCS2.Customer_Site_Id
INNER JOIN AR_Invoice_Item ARII2 ON ARII2.Invoice_Id = ARIN2.Invoice_Id
Inner JOIN SY_System SYSY2 On ARCSYS2.System_Id = SYSY2.System_Id
WHERE
ARIN2.Invoice_Date > dateadd(year, -1, getdate())
AND ARC2.Customer_Number = '300000'
AND ARII2.[Description] LIKE ('Warranty Credit')
OR ARII2.[Description] = ('Warranty Credit T')
GROUP BY ARII2.Amount
that returns the following results.
2031.00
1458.98
1272.50
620.00
160.00
My thought was that I could put a SUM around my Amount and it would return the desired value of 5542.48 (the total of the values).
SELECT
SUM(ARII2.Amount)
FROM
AR_Customer ARC2
Inner JOIN AR_Customer_Site ARCS2 On ARC2.Customer_Id = ARCS2.Customer_Id AND ARCS2.Customer_Id = ARC2.Customer_Id
INNER JOIN AR_Customer_System ARCSYS2 On ARCS2.Customer_Site_Id = ARCSYS2.Customer_Site_Id
INNER JOIN AR_Branch ARB2 ON ARB2.Branch_Id = ARC2.Branch_Id
INNER JOIN AR_Invoice ARIN2 ON ARIN2.Customer_Site_Id = ARCS2.Customer_Site_Id
INNER JOIN AR_Invoice_Item ARII2 ON ARII2.Invoice_Id = ARIN2.Invoice_Id
Inner JOIN SY_System SYSY2 On ARCSYS2.System_Id = SYSY2.System_Id
WHERE
ARIN2.Invoice_Date > dateadd(year, -1, getdate())
AND ARC2.Customer_Number = '300000'
--AND ARIN2.Invoice_Number = '204686'
AND ARII2.[Description] LIKE ('Warranty Credit')
OR ARII2.[Description] = ('Warranty Credit T')
GROUP BY ARII2.Amount, ARII2.[Description]
Which returned the following results which are not what I am looking for.
-10155.00
-7294.90
-6362.50
-3100.00
-800.00
As always any help on this is GREATLY appreciated!

You are getting multiple rows because of your GROUP BY. Remove that line, and you will only get the one total SUM.

Related

SQL Selects combine - Second select to be in Where clause

I have 2 selects. The first one:
select purs.t_orno as purchased
from ttisfc001201 sls
inner join twhinr110201 sfc on sfc.t_orno = sls.t_pdno
inner join twhltc100201 purs on purs.t_clot=sfc.t_clot
left join twhltc220201 items on items.t_clot = sfc.t_clot
left join twhltc210201 cert_num on cert_num.t_item = items.t_item
left join twhltc200201 cert on cert.t_ltft = cert_num.t_ltft
where sls.t_cprj = 'SLS004336' and purs.t_orno like N'PUR%'
and sfc.t_koor = 1 and sfc.t_kost = 5
Is giving me these results:
PUR007833
PUR008544
PUR008698
PUR008963
PUR009048
PUR009304
PUR009611
PUR009912
PUR009913
PUR010006
PUR010110
PUR010400
PUR010465
PUR010539
PUR010664
So basically these are results I must use in the second select in where clause. A field from table in second select must be equal to one of them. To understand me better it should look like this:
select distinct fac.t_isup
from ttfacp200201 fac
inner join ttfacp250201 mid on mid.t_ityp = fac.t_ttyp and mid.t_idoc=fac.t_ninv
where mid.t_orno ='PUR010400' or mid.t_orno='PUR009912'or mid.t_orno='PUR009913'or mid.t_orno='PUR010465'or mid.t_orno='PUR008544'or mid.t_orno='PUR008963'or mid.t_orno='PUR009048'or mid.t_orno='PUR010110'or mid.t_orno='PUR007833'or mid.t_orno='PUR009304'or mid.t_orno='PUR009611'or mid.t_orno='PUR010664'or mid.t_orno='PUR010006'or mid.t_orno='PUR010539'or mid.t_orno='PUR008698'or mid.t_orno='PUR010667'
All these ORs are results from the first select. How I can combine them (the first select to go in second select where clause) so I can get results at once?
You can use the IN clause for your second query
select distinct fac.t_isup
from ttfacp200201 fac
inner join ttfacp250201 mid on mid.t_ityp = fac.t_ttyp and mid.t_idoc=fac.t_ninv
where mid.t_orno IN (
select purs.t_orno
from ttisfc001201 sls
inner join twhinr110201 sfc on sfc.t_orno = sls.t_pdno
inner join twhltc100201 purs on purs.t_clot=sfc.t_clot
left join twhltc220201 items on items.t_clot = sfc.t_clot
left join twhltc210201 cert_num on cert_num.t_item = items.t_item
left join twhltc200201 cert on cert.t_ltft = cert_num.t_ltft
where sls.t_cprj = 'SLS004336' and purs.t_orno like N'PUR%'
and sfc.t_koor = 1 and sfc.t_kost = 5
)
Something like this
;with first_query_cte(purchased) as (
select purs.t_orno
from ttisfc001201 sls
inner join twhinr110201 sfc on sfc.t_orno = sls.t_pdno
inner join twhltc100201 purs on purs.t_clot=sfc.t_clot
left join twhltc220201 items on items.t_clot = sfc.t_clot
left join twhltc210201 cert_num on cert_num.t_item = items.t_item
left join twhltc200201 cert on cert.t_ltft = cert_num.t_ltft
where sls.t_cprj = 'SLS004336' and purs.t_orno like N'PUR%'
and sfc.t_koor = 1 and sfc.t_kost = 5)
select distinct fac.t_isup
from ttfacp200201 fac
inner join ttfacp250201 mid on mid.t_ityp = fac.t_ttyp and mid.t_idoc=fac.t_ninv
inner join first_query_cte fqc on mid.t_orno=fqc.purchased;

Access Query - Group by and Max

I have been working on this for a few hours now and just can not figure it out.
How would I go about sorting this query by enco_id and only having the max of each clpr_id show up. for example:
Here is my MSAccess Sql Code
SELECT dbo_Client.med_rec_no, dbo_Encounter.episode_number, dbo_client_program.enco_id, dbo_client_program.clpr_id, dbo_client_program.prle_id, dbo_PROGRAM_LEVEL.prle_name, dbo_Client.fname, dbo_Client.lname, dbo_DISCHARGE_STATUS.dist_name, DS2.dist_name
FROM (((((dbo_Client INNER JOIN dbo_Encounter ON dbo_Client.client_id = dbo_Encounter.client_id) INNER JOIN dbo_Episode_info ON dbo_Encounter.enco_id = dbo_Episode_info.enco_id) INNER JOIN dbo_DISCHARGE_STATUS ON dbo_Episode_info.dist_id = dbo_DISCHARGE_STATUS.dist_id) INNER JOIN dbo_client_program ON dbo_Encounter.enco_id = dbo_client_program.enco_id) INNER JOIN dbo_DISCHARGE_STATUS AS DS2 ON dbo_client_program.dist_id = DS2.dist_id) INNER JOIN dbo_PROGRAM_LEVEL ON dbo_client_program.prle_id = dbo_PROGRAM_LEVEL.prle_id;
Also here is what my query looks like
EDIT:
This is the code I am trying to use now and it still is not working
SELECT dbo_Client.client_id, dbo_Client.med_rec_no, dbo_Encounter.episode_number, dbo_Encounter.start_date, dbo_Encounter.end_date, dbo_client_program.clpr_id, dbo_client_program.enco_id, dbo_PROGRAM_LEVEL.prle_name, dbo_Client.fname, dbo_Client.lname, dbo_DISCHARGE_STATUS.dist_name, DS2.dist_name
FROM (((((dbo_Client INNER JOIN dbo_Encounter ON dbo_Client.client_id = dbo_Encounter.client_id) INNER JOIN dbo_Episode_info ON dbo_Encounter.enco_id = dbo_Episode_info.enco_id) INNER JOIN dbo_DISCHARGE_STATUS ON dbo_Episode_info.dist_id = dbo_DISCHARGE_STATUS.dist_id) INNER JOIN dbo_client_program ON dbo_Encounter.enco_id = dbo_client_program.enco_id) INNER JOIN dbo_DISCHARGE_STATUS AS DS2 ON dbo_client_program.dist_id = DS2.dist_id) INNER JOIN dbo_PROGRAM_LEVEL ON dbo_client_program.prle_id = dbo_PROGRAM_LEVEL.prle_id
WHERE dbo_client_program.clpr_id IN
(SELECT TOP 1 clpr_id FROM dbo_client_program as New
WHERE New.clpr_id = dbo_client_program.clpr_id
ORDER by dbo_client_program.clpr_id DESC) AND (dbo_DISCHARGE_STATUS.dist_name <> DS2.dist_name) AND dbo_Encounter.start_date > #1/1/2020# AND dbo_Encounter.end_date > #1/1/2020#
ORDER BY dbo_Encounter.episode_number;
As you are still understanding the aggregate queries my suggestion is:
1-Create a query where you group by all fields and max(clpr_id). Save this as "Query1"
2-Create another query based on "Query1" and sort by "enco_id "

Convert query select to a cursor

I need to convert my SQL Server query in a cursor.
I tried with the example of question Select statement in cursor but I had error.
Here my query:
SELECT DISTINCT
U.IDSocio, U.IDUtente,
U.Cognome, U.Nome, U.Sesso,
U.Luogo_Nascita,
U.Provincia_Nascita,
U.Stato_Nascita,
COALESCE(C.codice, SS.codice) as Nascita_CodCatastale,
CONVERT(DATE, U.Data_Nascita) AS Data_Nascita_Orig,
REPLACE(CONVERT(VARCHAR, U.Data_Nascita, 111), '/', '-') as Data_Nascita,
U.Indirizzo_Via as Residenza_Indirizzo,
U.Indirizzo_NumeroCivico as Residenza_NumeroCivico,
U.Indirizzo_Cap as Residenza_Cap,
U.Indirizzo_Citta as Residenza_Citta,
U.Indirizzo_Pv as Residenza_Provincia,
U.CodCatastaleResidenza as Residenza_CodCatastale,
U.Indirizzo_Stato as Residenza_Stato,
U.PIVA,
U.CodiceFiscale,
U.Documento,
U.Telefono_1,
U.Telefono_2,
U.SMS,
U.Email,
U.Note,
UG.Descrizione as Categoria,
U.AutorizzaSMS,
U.AutorizzaEmail,
U.AutorizzaCartaceo,
U.CFRicevuta,
U.CFRicevutaUtente
FROM [dbo].[Utenti] U
LEFT JOIN dbo.UtenteCustom UC on UC.IDUtente = U.IDUtente
LEFT JOIN dbo.UtentiCategorie UG on UG.IDCategoria = UC.IDCategoriaUtente
LEFT JOIN dbo.Comuni C on C.Comune = U.Luogo_Nascita and C.PV = U.Provincia_Nascita
LEFT JOIN dbo.Comuni SS on SS.Comune = U.Stato_Nascita
INNER JOIN dbo.AbbonamentiIscrizione AI ON U.IDUtente = AI.IDUtente
INNER JOIN dbo.AbbonamentiDurata AD ON AI.IDDurata = AD.IDDurata
INNER JOIN dbo.Abbonamenti A ON A.IDAbbonamento = AD.IDAbbonamento
INNER JOIN dbo.AziendeAbbonamenti AA On AA.IDAbbonamentoCategoria = A.IDCategoria
INNER JOIN dbo.TesseramentiAbbonamentiDurata TAD On TAD.IDDurata = AD.IDDurata
WHERE
COALESCE(AA.IDRicevutaAzienda, 2) = 2
AND (U.Cognome <> '' AND U.Nome <> '')
AND CONVERT(DATE, DataInizio) <= CONVERT(DATE, GETDATE())
AND CONVERT(DATE, DataFine) >= CONVERT(DATE, GETDATE())
ORDER BY U.IDUtente
Could you please help me to convert it into a cursor? I need to use a cursor because the query has many rows as result and the code that use it is too slow to execute.

SQL Query with counts only returning equivalent counts

I have a query that consists of 1 table and 2 sub queries. The table being a listing of all customers, 1 sub query is a listing all of the quotes given over a period of time for customers and the other sub query is a listing of all of the orders booked for a customer over the same period of time. What I am trying to do is return a result set that is a customer, the number of quotes given, and the number of orders booked over a given period of time. However what I am returning is only a listening of customers over the period of time that have an equivalent quote and order count. I feel like I am missing something obvious within the context of the query but I am unable to figure it out. Any help would be appreciated. Thank you.
Result Set should look like this
Customer-------Quotes-------Orders Placed
aaa----------------4----------------4
bbb----------------9----------------18
ccc----------------18----------------9
select
[Customer2].[Name] as [Customer2_Name],
(count( Quotes.UD03_Key3 )) as [Calculated_CustomerQuotes],
(count( Customer_Bookings.OrderHed_OrderNum )) as [Calculated_CustomerBookings]
from Erp.Customer as Customer2
left join (select
[UD03].[Key3] as [UD03_Key3],
[UD03].[Key4] as [UD03_Key4],
[UD03].[Key1] as [UD03_Key1],
[UD03].[Date02] as [UD03_Date02]
from Ice.UD03 as UD03
inner join Ice.UD02 as UD02 on
UD03.Company = UD02.Company
And
CAST(CAST(UD03.Number09 AS INT) AS VARCHAR(30)) = UD02.Key1
left outer join Erp.Customer as Customer on
UD03.Company = Customer.Company
And
UD03.Key1 = Customer.Name
left outer join Erp.SalesTer as SalesTer on
Customer.Company = SalesTer.Company
And
Customer.TerritoryID = SalesTer.TerritoryID
left outer join Erp.CustGrup as CustGrup on
Customer.Company = CustGrup.Company
And
Customer.GroupCode = CustGrup.GroupCode
where (UD03.Key3 <> '0')) as Quotes on
Customer2.Name = Quotes.UD03_Key1
left join (select
[Customer1].[Name] as [Customer1_Name],
[OrderHed].[OrderNum] as [OrderHed_OrderNum],
[OrderDtl].[OrderLine] as [OrderDtl_OrderLine],
[OrderHed].[OrderDate] as [OrderHed_OrderDate]
from Erp.OrderHed as OrderHed
inner join Erp.Customer as Customer1 on
OrderHed.Company = Customer1.Company
And
OrderHed.BTCustNum = Customer1.CustNum
inner join Erp.OrderDtl as OrderDtl on
OrderHed.Company = OrderDtl.Company
And
OrderHed.OrderNum = OrderDtl.OrderNum) as Customer_Bookings on
Customer2.Name = Customer_Bookings.Customer1_Name
where Quotes.UD03_Date02 >= '5/15/2018' and Quotes.UD03_Date02 <= '5/15/2018' and Customer_Bookings.OrderHed_OrderDate >='5/15/2018' and Customer_Bookings.OrderHed_OrderDate <= '5/15/2018'
group by [Customer2].[Name]
You have several problems going on here. The first problem is your code is so poorly formatted it is user hostile to look at. Then you have left joins being logically treated an inner joins because of the where clause. You also have date literal strings in language specific format. This should always be the ANSI format YYYYMMDD. But in your case your two predicates are contradicting each other. You have where UD03_Date02 is simultaneously greater than and less than the same date. Thankfully you have =. But if your column is a datetime you have prevented any rows from being returned again (the first being your where clause). You have this same incorrect date logic and join in the second subquery as well.
Here is what your query might look like with some formatting so you can see what is going on. Please note I fixed the logical join issue. You still have the date problems because I don't know what you are trying to accomplish there.
select
[Customer2].[Name] as [Customer2_Name],
count(Quotes.UD03_Key3) as [Calculated_CustomerQuotes],
count(Customer_Bookings.OrderHed_OrderNum) as [Calculated_CustomerBookings]
from Erp.Customer as Customer2
left join
(
select
[UD03].[Key3] as [UD03_Key3],
[UD03].[Key4] as [UD03_Key4],
[UD03].[Key1] as [UD03_Key1],
[UD03].[Date02] as [UD03_Date02]
from Ice.UD03 as UD03
inner join Ice.UD02 as UD02 on UD03.Company = UD02.Company
And CAST(CAST(UD03.Number09 AS INT) AS VARCHAR(30)) = UD02.Key1
left outer join Erp.Customer as Customer on UD03.Company = Customer.Company
And UD03.Key1 = Customer.Name
left outer join Erp.SalesTer as SalesTer on Customer.Company = SalesTer.Company
And Customer.TerritoryID = SalesTer.TerritoryID
left outer join Erp.CustGrup as CustGrup on Customer.Company = CustGrup.Company
And Customer.GroupCode = CustGrup.GroupCode
where UD03.Key3 <> '0'
) as Quotes on Customer2.Name = Quotes.UD03_Key1
and Quotes.UD03_Date02 >= '20180515'
and Quotes.UD03_Date02 <= '20180515'
left join
(
select
[Customer1].[Name] as [Customer1_Name],
[OrderHed].[OrderNum] as [OrderHed_OrderNum],
[OrderDtl].[OrderLine] as [OrderDtl_OrderLine],
[OrderHed].[OrderDate] as [OrderHed_OrderDate]
from Erp.OrderHed as OrderHed
inner join Erp.Customer as Customer1 on OrderHed.Company = Customer1.Company
And OrderHed.BTCustNum = Customer1.CustNum
inner join Erp.OrderDtl as OrderDtl on OrderHed.Company = OrderDtl.Company
And OrderHed.OrderNum = OrderDtl.OrderNum
) as Customer_Bookings on Customer2.Name = Customer_Bookings.Customer1_Name
and Customer_Bookings.OrderHed_OrderDate >= '20180515'
and Customer_Bookings.OrderHed_OrderDate <= '20180515'
group by [Customer2].[Name]
COUNT() will just give you the number of records. You'd expect this two result columns to be equal. Try structuring it like this:
SUM(CASE WHEN Quote.UD03_Key1 IS NOT NULL THEN 1 ELSE 0 END) AS QuoteCount,
SUM(CASE WHEN Customer_Bookings.Customer1_Name IS NOT NULL THEN 1 ELSE 0 END) AS custBookingCount

incorrect syntax near the keyword where for using subquery

SELECT DISTINCT dbo.master_order.order_no,
dbo.master_order.program_no,
dbo.Setup_size.size_name,
dbo.Setup_color.color_name,
dbo.Setup_color.color_no,
dbo.transaction_production.total_weight,
dbo.Setup_yarn.yarn_count,
dbo.Setup_article_order.article_name,
dbo.master_order.shipment_date,
#from AS reprt,
#to AS reprt1,
dbo.transaction_order.quantity,
dbo.transaction_order.gsm
FROM dbo.master_order
INNER JOIN dbo.transaction_order ON dbo.master_order.order_id = dbo.transaction_order.order_id
INNER JOIN dbo.transaction_production ON dbo.transaction_order.trans_id = dbo.transaction_production.trans_id
INNER JOIN dbo.Setup_size ON dbo.transaction_order.size_id = dbo.Setup_size.size_id
INNER JOIN dbo.Setup_yarn ON dbo.transaction_order.yarn_id = dbo.Setup_yarn.yarn_id
INNER JOIN dbo.Setup_article_order ON dbo.transaction_order.article_id = dbo.Setup_article_order.article_id
INNER JOIN dbo.Setup_color ON dbo.transaction_order.color_id = dbo.Setup_color.color_id
AND dbo.Setup_yarn.color_id = dbo.Setup_color.color_id
WHERE dbo.setup_color.color_id=
(SELECT color_no
FROM dbo.setup_color) WHERE master_order.shipment_date>=#from
AND master_order.shipment_date<=#to
This is your syntax after WHERE clause
where dbo.setup_color.color_id=
(select color_no from dbo.setup_color)
where master_order.shipment_date>=
#from and master_order.shipment_date<=#to
there are 2 Where clauses used on main Query.
use in instead of equals for a subquery.
SELECT DISTINCT
dbo.master_order.order_no,
dbo.master_order.program_no,
dbo.Setup_size.size_name,
dbo.Setup_color.color_name,
dbo.Setup_color.color_no,
dbo.transaction_production.total_weight,
dbo.Setup_yarn.yarn_count,
dbo.Setup_article_order.article_name,
dbo.master_order.shipment_date,
#from as reprt,
#to as reprt1,
dbo.transaction_order.quantity,
dbo.transaction_order.gsm
FROM dbo.master_order
INNER JOIN dbo.transaction_order ON dbo.master_order.order_id = dbo.transaction_order.order_id
INNER JOIN dbo.transaction_production ON dbo.transaction_order.trans_id = dbo.transaction_production.trans_id
INNER JOIN dbo.Setup_size ON dbo.transaction_order.size_id = dbo.Setup_size.size_id
INNER JOIN dbo.Setup_yarn ON dbo.transaction_order.yarn_id = dbo.Setup_yarn.yarn_id
INNER JOIN dbo.Setup_article_order ON dbo.transaction_order.article_id = dbo.Setup_article_order.article_id
INNER JOIN dbo.Setup_color ON dbo.transaction_order.color_id = dbo.Setup_color.color_id
AND dbo.Setup_yarn.color_id = dbo.Setup_color.color_id where dbo.setup_color.color_id in
(select color_no from dbo.setup_color) where master_order.shipment_date >= #from and master_order.shipment_date<= #to
The problem is that you have 2 WHERE clauses in the main query. as master_order is a table used in main query, just replace 2nd WHERE withAND as below.
SELECT DISTINCT dbo.master_order.order_no,
dbo.master_order.program_no,
dbo.Setup_size.size_name,
dbo.Setup_color.color_name,
dbo.Setup_color.color_no,
dbo.transaction_production.total_weight,
dbo.Setup_yarn.yarn_count,
dbo.Setup_article_order.article_name,
dbo.master_order.shipment_date,
#from AS reprt,
#to AS reprt1,
dbo.transaction_order.quantity,
dbo.transaction_order.gsm
FROM dbo.master_order
INNER JOIN dbo.transaction_order ON dbo.master_order.order_id = dbo.transaction_order.order_id
INNER JOIN dbo.transaction_production ON dbo.transaction_order.trans_id = dbo.transaction_production.trans_id
INNER JOIN dbo.Setup_size ON dbo.transaction_order.size_id = dbo.Setup_size.size_id
INNER JOIN dbo.Setup_yarn ON dbo.transaction_order.yarn_id = dbo.Setup_yarn.yarn_id
INNER JOIN dbo.Setup_article_order ON dbo.transaction_order.article_id = dbo.Setup_article_order.article_id
INNER JOIN dbo.Setup_color ON dbo.transaction_order.color_id = dbo.Setup_color.color_id
AND dbo.Setup_yarn.color_id = dbo.Setup_color.color_id
WHERE dbo.setup_color.color_id=
(SELECT color_no
FROM dbo.setup_color)
AND master_order.shipment_date>=#from
AND master_order.shipment_date<=#to
Also if the table dbo.setup_color has more than 1 value, either use IN instead of = or add a WHERE clause to the inner query to return just one value, otherwise it will throw error.