SQL Query returning multiple Duplicate Results - sql

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

Related

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

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

How do i sum two query with each count and criteria in it

I have this two query sql and i'm trying to do a sum of both 2 counts in the query together but when i try to do the UNION ALL but it kept prompt me to enter parameter for CountOfTools_Number2. All i wan is the sum of the two count and return me a value.
SELECT Count(Test.Tool_Number) AS CountOfTool_Number1
FROM Test INNER JOIN Test_Tool ON Test.Tool_Number = Test_Tool.Current_Tool
GROUP BY Test_Tool.Current_Test
HAVING (((Test_Tool.Current_Test) Like "*E1*"));
SELECT Count(Test.Tool_Number) AS CountOfTool_Number2
FROM Test_Tool, Test INNER JOIN Previous_Tool ON Test.Tool_Number = Previous_Tool.Previous_Tool
GROUP BY Test_Tool.Current_Test
HAVING (((Test_Tool.Current_Test) Like "*E1*"));
Presuming your two example queries work, this should do the trick:
select
sum(CountOfTool_Number1) as CountOfTool
from (
SELECT Count(Test.Tool_Number) AS CountOfTool_Number1
FROM Test INNER JOIN Test_Tool ON Test.Tool_Number = Test_Tool.Current_Tool
GROUP BY Test_Tool.Current_Test
HAVING (((Test_Tool.Current_Test) Like "*E1*"))
union all
SELECT Count(Test.Tool_Number) AS CountOfTool_Number2
FROM Test_Tool, Test INNER JOIN Previous_Tool ON Test.Tool_Number = Previous_Tool.Previous_Tool
GROUP BY Test_Tool.Current_Test
HAVING (((Test_Tool.Current_Test) Like "*E1*"))
) as q;

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 Server Query for Many to Many Relationship

I have the following Many to many relationship (See the picture below) in my SQL server.
In most cases there's are 2 rows in table tblWavelengths related to the table tblSensors, (in some cases only 1, and in extreme cases there can be 20 rows)
I made the following simple query to retrieve the data from those 3 tables :
select W.DateTimeID,S.SensorName,S.SensorType,W.Channel,W.PeakNr,W.Wavelength
from tblWavelengths as W
Left Join tblSensorWavelengths as SW on W.tblWavelengthID = SW.WavelengthID
Left Join tblSensors as S on SW.SensorID = S.SensorID
order by W.DateTimeID
After running this query I got the following results :
Here comes my problem. I want to write a query which filters only those Sensors (SensorName) which at a given moment in time (DateTimeID) has two rows (two different wavelengths) in the tblWavelengths table. So for example I want to have the results without
the 77902/001 Sensor - because it has only one row (one Wavelength) related to the tblSensors at a given moment in time
You could use a windowed function to find out the number of wavelengths for each sensorname/datetimeid combination:
WITH Data AS
( SELECT W.DateTimeID,
S.SensorName,
S.SensorType,
W.Channel,
W.PeakNr,
W.Wavelength,
[Wcount] = COUNT(*) OVER(PARTITION BY s.SensorName, d.DateTimeID)
from tblWavelengths as W
LEFT JOIN tblSensorWavelengths as SW
ON W.tblWavelengthID = SW.WavelengthID
LEFT JOIN tblSensors as S
ON SW.SensorID = S.SensorID
)
SELECT DateTimeID, SensorName, SensorType, Channel, PeakNr, WaveLength
FROM Data
WHERE Wcount = 2
ORDER BY DateTimeID;
ADDENDUM
As an after thought I realised that you might have two results for one sensor at the same time with the same wavelength, which would return 2 records, but not have two different wavelengths. Since windowed functions don't support the use of DISTINCT an alternative is below
WITH Data AS
( SELECT W.DateTimeID,
S.SensorName,
S.SensorType,
W.Channel,
W.PeakNr,
W.Wavelength,
W.tblWaveLengthID
from tblWavelengths as W
LEFT JOIN tblSensorWavelengths as SW
ON W.tblWavelengthID = SW.WavelengthID
LEFT JOIN tblSensors as S
ON SW.SensorID = S.SensorID
)
SELECT d.DateTimeID, d.SensorName, d.SensorType, d.Channel, d.PeakNr, d.WaveLength
FROM Data d
INNER JOIN
( SELECT DateTimeID, SensorName
FROM Data
GROUP BY DateTimeID, SensorName
HAVING COUNT(DISTINCT tblWaveLengthID) = 2
) t
ON t.DateTimeID = d.DateTimeID
AND t.SensorName = d.SensorName
ORDER BY d.DateTimeID;

SQL Selecting based off largest date from different table

I am attempting to write a query that pulls Order information from various tables. I have hit a road block at the target date value.
It seems that every time a target date is changed a new row is added in that table. All I want is to be able to select only the newest Target Date. What should I do?
select Distinct
OR01001 AS OrderNumber,
OR01002 AS OrderType,
OR01003 AS CustomerCode,
OR01015 AS OrderDate,
OR01017 AS CustomerREP,
OR01018 AS ContactPerson,
OR01019 AS SalesmanNumber,
OR03011 - OR03012 AS OpenQuantity,
SC03003 AS StockBalance,
OR01050 AS WarehouseNumber,
OR01072 AS CustomerPO,
OR03005 AS ItemCode,
OR03002 AS LineNumber,
OR500100.OR50004 As TargetDate
from OR010100
INNER Join OR030100 ON OR030100.OR03001 = OR010100.OR01001
INNER Join SL010100 ON SL010100.SL01001 = OR010100.OR01003
INNER Join SC030100 ON SC030100.SC03001 = OR030100.OR03005
Inner JOIN OR500100 ON OR500100.OR50001 = OR010100.OR01001
where OR010100.OR01002 <> 0 AND OR010100.OR01002 <> 6 AND OR01017 = 'SLOTT'
Order by OR01017 ASC;
If I understand your columns correctly, here's one way:
SELECT ...,
OR500100A.OR50004 AS TargetDate
FROM ...
INNER JOIN OR500100 AS OR500100A ON OR500100A.OR50001 = OR010100.OR01001
AND NOT EXISTS(SELECT 1 FROM OR500100 AS OR500100B
WHERE OR500100B.OR5001 = OR010100.OR01001
AND OR500100B.OR50004 > OR500100A.OR50004)
...
This makes sure you only get one OR500100 row with the latest value in OR50004 for the given OR5001.
from what i understand,
SELECT
...
MAX(OR500100.OR50004) As TargetDate
FROM...
WHERE...
GROUP BY --everything but OR500100.OR50004
ORDER BY...
should do the trick
EDIT: ty Ic.