Error getting the amount grouped by name and account number SQL Server - sql

I have an issue on my SQL query. I tried doing two ways
With the first query I got the right amount but I lose some name descriptions
With the second I got every name descriptions but I got a lower amount.
Context: I want to get the revenue gotten between two dates.
I need the following columns from tables
Table reciboDet I need the columns CtaIngreso, ValorUnitReciboDet
Table CuentaIngreso_A the column nombrectaingreso, ctaingreso (only to create the join)
Table Recibo the columns FechaRecibo and ReciboAnulado
To get the right name descriptions I need to verify the receipt year that was in the table AvpgEnc, but when I do that a lose the amount.
First query
SELECT
ReciboDet.CtaIngreso
, SUM(ReciboDet.ValorUnitReciboDet) AS Total
, CuentaIngreso_A.NombreCtaIngreso
FROM
ReciboDet
INNER JOIN CuentaIngreso_A
ON ReciboDet.CtaIngreso = CuentaIngreso_A.CtaIngreso
WHERE
(ReciboDet.NumRecibo IN
(SELECT NumRecibo
FROM Recibo
WHERE (FechaRecibo BETWEEN '01/10/2020' AND '31/10/2020')
AND (ReciboAnulado = 0)
AND (CuentaIngreso_A.Anio = DATEPART(year, FechaRecibo))
)
)
GROUP BY
ReciboDet.CtaIngreso
, CuentaIngreso_A.NombreCtaIngreso
ORDER BY
CuentaIngreso_A.NombreCtaIngreso
Second query
SELECT
ReciboDet.CtaIngreso [cuenta],
sum(ReciboDet.ValorUnitReciboDet) [monto],
CuentaIngreso_A.NombreCtaIngreso [descripcion]
FROM
ReciboDet
inner join avpgenc
on ReciboDet.NumFactura = AvPgEnc.NumAvPg
inner join CuentaIngreso_A
on ReciboDet.CtaIngreso = CuentaIngreso_A.CtaIngreso
WHERE
(ReciboDet.NumRecibo IN
(SELECT NumRecibo
FROM Recibo
WHERE (FechaRecibo BETWEEN '01/10/2020' AND '31/10/2020')
AND (ReciboAnulado = 0)
)
AND (year(AvPgEnc.FechaVenceAvPg) = CuentaIngreso_A.Anio)
)
GROUP BY
ReciboDet.CtaIngreso
, CuentaIngreso_A.NombreCtaIngreso
ORDER BY
ReciboDet.CtaIngreso

Related

SQL - Summarizing Monthly Sales Data

I have two tables that I need to combine, but I can't get to seem the joins to work. The picture has three tables
_date_array2: Has a field DateMonthYr that contains all possible date/yr combinations
_sales_summ_tbl__ => Has 5 fields. Only months with sales show up. For example, you see only three records showing up for the second table. There is no 5/2016, for example, because there were no sales for that month.
My goal is to "pad" the second table to have TotalDemand of 0's for months with no sales. I am very close (see the third table), except I cannot get the PartNumber to show up for dates with no sales.
My guess is that it's due to the RIGHT JOIN. But I'm not sure how to handle this. The output I am hoping for is table 3 but with the part number populated for all entries.
And here is my code (the results from running this code are the third/last table in the picture):
SELECT TmpSalesTbl.PartNumber as PartNumber,
tmp_date_array.CreateDateMonth as CreateDateMonth,
tmp_date_array.CreateDateYear as CreateDateYear,
CASE WHEN TmpSalesTbl.TotalDemand is NULL THEN 0 ELSE TmpSalesTbl.TotalDemand END as TotalDemand
FROM #_sales_summ_tbl__ TmpSalesTbl
RIGHT JOIN #_date_array2 tmp_date_array on tmp_date_array.CreateDateMonthYr = TmpSalesTbl.CreateDateMonthYr
ORDER BY tmp_date_array.CreateDateYear, tmp_date_array.CreateDateMonth
It is more conventional to place the list of all dates first, then left join to the data and whilst using a case expression is fine an alternative is coalesce(). This should ensure all the wanted months/years display:
SELECT
tmpsalestbl.PartNumber AS partnumber
, tmp_date_array.CreateDateMonth AS createdatemonth
, tmp_date_array.CreateDateYear AS createdateyear
, COALESCE(tmpsalestbl.TotalDemand, 0) AS totaldemand
FROM #_date_array2 tmp_date_array
LEFT JOIN #_sales_summ_tbl__ tmpsalestbl ON tmp_date_array.CreateDateMonthYr = tmpsalestbl.CreateDateMonthYr
ORDER BY
tmp_date_array.CreateDateYear
, tmp_date_array.CreateDateMonth
To populate for evey partnumber, on every month, you will need a new subquery:
select distinct PartNumber #_sales_summ_tbl__
And then cross join that to the years/months so you have a complete set of years/months/parts.
SELECT
cj.PartNumber AS partnumber
, tmp_date_array.CreateDateMonth AS createdatemonth
, tmp_date_array.CreateDateYear AS createdateyear
, COALESCE(tmpsalestbl.TotalDemand, 0) AS totaldemand
FROM #_date_array2 tmp_date_array
CROSS JOIN (
SELECT DISTINCT
PartNumber FROM #_sales_summ_tbl__
) cj
LEFT JOIN #_sales_summ_tbl__ tmpsalestbl ON tmp_date_array.CreateDateMonthYr = tmpsalestbl.CreateDateMonthYr
AND cj.PartNumber = tmpsalestbl.PartNumber
ORDER BY
tmp_date_array.CreateDateYear
, tmp_date_array.CreateDateMonth
;

Access Crosstab Query: based on sales totals within TWO date ranges

I'm looking for a way to create an Access crosstab query reporting sales totals by 'Brand', for two different date ranges.:
For Distributor: "DistID" (column, not visible)
Sales Totals: "Sales" (column)
TWO different date ranges: "depDate" for Period 1 and Period 2 (column):
Period1 = Between [forms]![frmRPT_YTDDepl_SF]![BDT1] And [forms]![frmRPT_YTDDepl_SF]![EDT1]
Period2 = Between [forms]![frmRPT_YTDDepl_SF]![BDT2] And [forms]![frmRPT_YTDDepl_SF]![EDT2]
Brands = "DprodBrand" (rows)
Currently, I have TWO separate crosstab queries for each period, working properly. -> CODE BELOW.
I am looking for a way to create ONE query displaying Brand's sales totals for each date range, in two separate columns or one crosstab query.
Period1:
TRANSFORM Sum(tblDepletions_DETAIL.detQuan) AS Sales
SELECT tblProducts_DEPL.DprodBrand
FROM tblDepletions INNER JOIN (tblProducts_DEPL INNER JOIN tblDepletions_DETAIL ON tblProducts_DEPL.DprodZSKU = tblDepletions_DETAIL.detZSKU) ON tblDepletions.depID = tblDepletions_DETAIL.detDeplID
WHERE (((tblDepletions.depDate) Between [forms]![frmRPT_YTDDepl_SF]![BDT1] And [forms]![frmRPT_YTDDepl_SF]![EDT1]) AND ((tblDepletions.depDistID)=132))
GROUP BY tblProducts_DEPL.DprodBrand
ORDER BY tblProducts_DEPL.DprodBrand
PIVOT Format([depDate],"yy")-(Format(Date(),"yy"))+2 In (1,2);
Period2:
TRANSFORM Sum(tblDepletions_DETAIL.detQuan) AS Sales
SELECT tblProducts_DEPL.DprodBrand
FROM tblDepletions INNER JOIN (tblProducts_DEPL INNER JOIN tblDepletions_DETAIL ON tblProducts_DEPL.DprodZSKU = tblDepletions_DETAIL.detZSKU) ON tblDepletions.depID = tblDepletions_DETAIL.detDeplID
WHERE (((tblDepletions.depDate) Between [forms]![frmRPT_YTDDepl_SF]![BDT2] And [forms]![frmRPT_YTDDepl_SF]![EDT2]) AND ((tblDepletions.depDistID)=132))
GROUP BY tblProducts_DEPL.DprodBrand
ORDER BY tblProducts_DEPL.DprodBrand
PIVOT Format([depDate],"yy")-(Format(Date(),"yy"))+2 In (1,2);
Many Thanks!!! ~~ Jacob
Consider simply joining the two saved, crosstab queries like any other pair of queries or tables using the DprodBrand as join key:
SELECT CrosstabQ1.DprodBrand,
CrosstabQ1.[1] As Period1_Year1, CrosstabQ2.[1] As Period2_Year1,
CrosstabQ1.[2] As Period1_Year2, CrosstabQ2.[2] As Period2_Year2
FROM CrosstabQ1
INNER JOIN CrosstabQ2 ON CrosstabQ1.DprodBrand = CrosstabQ2.DprodBrand
Now if you only want one query to do it all, consider the conditional aggregate pivot query since crosstabs cannot be used as subqueries. Here you migrate WHERE to IIF() conditions:
SELECT p.DprodBrand,
SUM(IIF((d.depDate BETWEEN [Forms]![frmRPT_YTDDepl_SF]![BDT1]
AND [Forms]![frmRPT_YTDDepl_SF]![EDT1])
AND (Format(d.[depDate],"yy")-(Format(Date(),"yy"))+2 = 1),
dt.detQuan, NULL)) AS Period1_Year1,
SUM(IIF((d.depDate BETWEEN [Forms]![frmRPT_YTDDepl_SF]![BDT2]
AND [Forms]![frmRPT_YTDDepl_SF]![EDT2)
AND (Format(d.[depDate],"yy")-(Format(Date(),"yy"))+2 = 1),
dt.detQuan, NULL)) AS Period2_Year1,
SUM(IIF((d.depDate BETWEEN [Forms]![frmRPT_YTDDepl_SF]![BDT1]
AND [Forms]![frmRPT_YTDDepl_SF]![EDT1])
AND (Format(d.[depDate],"yy")-(Format(Date(),"yy"))+2 = 2),
dt.detQuan, NULL)) AS Period1_Year2,
SUM(IIF((d.depDate BETWEEN [Forms]![frmRPT_YTDDepl_SF]![BDT2]
AND [Forms]![frmRPT_YTDDepl_SF]![EDT2])
AND (Format(d.[depDate],"yy")-(Format(Date(),"yy"))+2 = 2),
dt.detQuan, NULL)) AS Period2_Year2
FROM tblDepletions d
INNER JOIN (tblProducts_DEPL p
INNER JOIN tblDepletions_DETAIL dt
ON p.DprodZSKU = dt.detZSKU)
ON d.depID = dt.detDeplID
WHERE ((d.depDistID)=132)
GROUP BY p.DprodBrand
ORDER BY p.DprodBrand
As this is Access, it might be simpler to save the two queries leaving out the ORDER BY.
Then create a new query:
SELECT *
FROM Q1
UNION ALL
SELECT *
FROM Q2
ORDER BY DprodBrand
By: Dale Fye (Access MVP):
I'm not sure you need a CrossTab for this.
Select DProdBrand,
SUM(IIF([DepDate] BETWEEN [Forms]![frmRpt_YTDDepl_SF]![BDT1]
AND [[forms]![frmRPT_YTDDepl_SF]![EDT1], [Sales], 0) as Period1,
SUM(IIF([DepDate] Between [forms]![frmRPT_YTDDepl_SF]![BDT2]
AND [forms]![frmRPT_YTDDepl_SF]![EDT2], [Sales], 0) as Period2,
SUM([Sales]) as [Sales Total]
FROM yourTable
GROUP BY DProdBrand
https://www.experts-exchange.com/questions/28978325/Access-Crosstab-Query-based-on-sales-totals-within-TWO-date-ranges.html

Combine two SQL Queries to prevent having to use a loop

I need to combine two SQL Queries and I'm hurting myself trying to think through it. My first query gets the number of visitors per day and the second query gets the number of unique visitors per day.
Query 1 - For getting the number of visits
SELECT Count(server_instances.game_id) AS visit_count,
refined_player_visits.visit_date AS visit_date
FROM work.refined_player_visits
INNER JOIN tapi.server_instances
ON server_instances.server_id = refined_player_visits.server_id
WHERE ( server_instances.game_id = "31" )
GROUP BY visit_date;
Query 2 - For getting the number of unique visits
SELECT Count(visit_counts.unique_visit_date) AS unique_visits
FROM (SELECT Count(refined_player_visits.server_id) AS visit_count,
refined_player_visits.visit_date AS unique_visit_date
FROM refined_player_visits
INNER JOIN server_instances
ON server_instances.server_id =
refined_player_visits.server_id
WHERE ( server_instances.place_id = "31"
AND refined_player_visits.visit_date <= CURRENT_VISIT_DATE )
GROUP BY refined_player_visits.roblox_id) AS visit_counts
WHERE ( visit_counts.visit_date = CURRENT_VISIT_DATE
AND visit_counts.visit_count = 1 )
Because this was originally for a web application, I got the results back from the first query and looped through each one. During each loop I would do the second query (where CURRENT_VISIT_DATE is actually the visit_date from the first query.
I'd like to turn this into one query using a JOIN, perhaps. I'm migrating to another system and I don't have the option of doing a second query in the loop statement, so I want to just combine the two queries. I can't seem to wrap my head around it, though.
Does this return what you want?
SELECT *
FROM
(
SELECT Count(server_instances.game_id) AS visit_count,
refined_player_visits.visit_date AS visit_date
FROM work.refined_player_visits
INNER JOIN tapi.server_instances
ON server_instances.server_id = refined_player_visits.server_id
WHERE ( server_instances.game_id = "31" )
GROUP BY visit_date
) AS FirstQuery,
(
SELECT Count(visit_counts.unique_visit_date) AS unique_visits
FROM (SELECT Count(refined_player_visits.server_id) AS visit_count,
refined_player_visits.visit_date AS unique_visit_date
FROM refined_player_visits
INNER JOIN server_instances
ON server_instances.server_id =
refined_player_visits.server_id
WHERE (server_instances.place_id = "31"
AND refined_player_visits.visit_date <= FirstQuery.visit_date)
GROUP BY refined_player_visits.roblox_id) AS visit_counts
WHERE ( visit_counts.visit_date = FirstQuery.visit_date
AND visit_counts.visit_count = 1 )
) AS SecondQuery

SQL Query returning multiple Duplicate Results

scenario : I have Three Tables(Prisoners,AddPaymentTransaction,WithdrawPaymentTransation)
Date in Tables : i have 1 row of prisoner with PrisonerID=5 and two rows in both other table,
i have wrote query to return there data if any prisoner have add some payment in there account or with draw any payment from there payment on same day or on different dates etc.
here is my query :
select at.PrisonerID ,at.Amount as AAmount,at.Date as ADate,wt.Amount as WAmount,wt.Date as WDate
from Prisoners p, AddPaymentTransaction at,WithdrawPaymentTransation wt
where p.PrisonerID=at.PrisonerID and p.PrisonerID=wt.PrisonerID and at.PrisonerID=wt.PrisonerID and at.PrisonerID=5
but it gives me 4 rows, 9 rows when i have 3 rows of data in each Table etc.
i want rows of data with out duplicate. any suggestions or help will be highly appreciated.
It looks like at.PrisonerID = wt.PrisonerID in your query might be what is causing all of the duplicates. I am guessing AddPaymentTransaction and WithdrawPaymentTransation should not be linked together. So, how about the following:
SELECT at.PrisonerID, at.Amount as AAmount, at.Date as ADate,
wt.Amount as WAmount, wt.Date as WDate
FROM Prisoners p
INNER JOIN AddPaymentTransaction at p.PrisonerID = at.PrisonerID
INNER JOIN WithdrawPaymentTransation wt ON p.PrisonerID = wt.PrisonerID
WHERE at.PrisonerID = 5
but this probably isn't going to give you exactly what you are looking for either. So maybe something like the following:
SELECT * FROM
(
SELECT p.PrisonerID, 'AddPayment' AS Type,
apt.Amount as TransAmount, apt.Date AS TransDate
FROM Prisoners p
INNER JOIN AddPaymentTransaction apt ON p.PrisonerID = apt.PrisonerID
WHERE apt.PrisonerID = 5
UNION
SELECT p.PrisonerID, 'WithdrawPayment' AS Type,
wt.Amount as TransAmount, wt.Date as TransDate
FROM Prisoners p
INNER JOIN WithdrawPaymentTransation wt ON p.PrisonerID = wt.PrisonerID
WHERE wt.PrisonerID = 5
) AS mq
ORDER BY mq.TransDate DESC

Records repeat for SSRS 2005 report

When I run a report for a purchase order, the report duplicates records for product codes.
For example the purchase order is: P000976, the report display the product code twice when it should only appear once. 45-5540 appears twice.
P000976 09-17-2012 15,040.00 15,040.00 0.00
45-5540 "Lordotic Cervical Spacer 10mm
Lordotic Cervical Spacer 10mm" 20 20 0
45-5540 "Lordotic Cervical Spacer 10mm
Lordotic Cervical Spacer 10mm" 20 20 0
When I put the report's SQL in SQL server and run the sql by seeing where the code cause the additional product code it is this line within the SQL:
join all_product_codes_VW p on q.distpartno = p.distpartno
select q.specialrequirement
, q.distpartno
, q.toproduce
, q.prodbegindate
, q.distributor
, rc.report_category_name
, s.productperpo
, r.ebi_released
, w.ebi_in_WIP
, p.distproductname
, tp.typeprefixdetail
, tp.cost
, '1' as ReportTotals
from all_required_vw q
left join all_shipped_grafts_new_VW s on (q.distpartno = s.distpartno and q.specialrequirement = s.ponumber)
left join all_released_Grafts_VW r on q.distpartno = r.distpartno
left join all_in_WIP_VW w on q.distpartno = w.distpartno
join all_product_codes_VW p on q.distpartno = p.distpartno
join setup_tissue_prefix tp on q.typenumber = tp.typeprefix
join setup_report_category_1 rc on q.distributor = rc.report_category_id
where q.prodbegindate < #enddate
and q.completed = '0'
and rc.report_category_name like '%' + isnull(#tcustomer, '') + '%'
order by q.prodbegindate, p.distproductname
This is the SQL for the view for which the join creates the duplicate.
SELECT COUNT_BIG(*) AS BIG, DistPartNo, DistProductName, Distributor, UMTBProductCode
FROM dbo.Setup_Distributor_Product_info
WHERE (Distributor <> '7') OR (Distributor IS NULL)
GROUP BY DistPartNo, DistProductName, Distributor, USSAProductCode
If you comment out these lines
--, p.distproductname
--join all_product_codes_VW p on q.distpartno = p.distpartno
Does the query return single rows for each distpartno? If yes then you're right that the all_products_code_VW view is causing the multiple rows.
Run these two queries and look at how many rows are in each and it will give you a clue as to why this is:
Select * from all_required_vw where distpartno = '45-5540'
Select * from all_product_codes_VW where distpartno = '45-5540'
My guess is that joining on only the distpartno is not enough to give you unique results. There might be more than one distributor for the same part, or multiple productnames for the same part number, e.g. different distrubutors using the the same part number with different products.
Possible this GROUP BY clause
GROUP BY DistPartNo, DistProductName, Distributor, USSAProductCode
need replace on this
GROUP BY DistPartNo, DistProductName, Distributor, UMTBProductCode