I am looking to get a count of total number of active employees for 2022 and 2023.
Our tables have records on a weekly basis, so when I am pulling the records, its counting an employee 52 times . I am looking to have the query count based on if the person has an active record within the year, to have it only count once. I have includes distinct in the select statement but still getting multiple counts and its not really duplicate so distinct is probable not the solution here.
select distinct count(*)
from TimeSheetsView TSV
inner join Person_Identification PI on PI.PersonId=TSV.Personid
inner join Order_Person_Detail_Record OPDR on OPDR.PersonId=Pi.PersonId and OPDR.DetailRecId=TSV.DetailRecId and OPDR.OrderId=TSV.orderid
where PI.PersonType='AS' and tsv.recordtype='A' and left(yearweek,4) IN ( '2022')
group by PI.PersonId
You shouldn't take "PI" as an alias, since PI is a reserved word.
Simply take DISTINCT within the brackets of the COUNT aggregation, you do not need to group:
SELECT
COUNT(DISTINCT PI.PersonId) AS "Total Count"
FROM TimeSheetsView TSV
INNER JOIN Person_Identification P ON P.PersonId=TSV.Personid
INNER JOIN Order_Person_Detail_Record OPDR
ON OPDR.PersonId=P.PersonId
AND OPDR.DetailRecId=TSV.DetailRecId
AND OPDR.OrderId=TSV.orderid
WHERE P.PersonType='AS'
AND tsv.recordtype='A'
AND left(yearweek,4) IN ( '2022');
If you want to see the Totals per Year, you can use:
SELECT
LEFT(yearweek,4) AS "Year",
COUNT(DISTINCT PI.PersonId) AS "Total Count"
FROM TimeSheetsView TSV
INNER JOIN Person_Identification P ON P.PersonId=TSV.Personid
INNER JOIN Order_Person_Detail_Record OPDR
ON OPDR.PersonId=P.PersonId
AND OPDR.DetailRecId=TSV.DetailRecId
AND OPDR.OrderId=TSV.orderid
WHERE P.PersonType='AS' AND tsv.recordtype='A'
GROUP BY LEFT(yearweek,4);
Related
Task: write a query to generate the total number of invoices, the invoice total for all of the invoices, the smallest invoice amount, the largest invoice amount, and the average of all of the invoices.
My attempt so far:
SELECT
COUNT(DISTINCT Lines.inv_number) as NumberOfInvoices,
SUM(Lines.line_price * Lines.line_units) as TotalSales,
MIN(SELECT SUM(Lines.line_price * Lines.line_units)
FROM dbo.Lines
INNER JOIN dbo.Invoices ON Invoices.inv_number = Lines.inv_number
GROUP BY Invoices.cus_code) as MinimumSale,
MAX(Lines.line_price * Lines.line_units) as LargestSale,
AVG(Lines.line_price * Lines.line_units) as AverageSale
FROM
dbo.Lines
INNER JOIN
dbo.Invoices ON Invoices.inv_number = Lines.inv_number;
I keep getting an error when running. Not sure if I am putting the subquery in the right place.
You can use subquery as below:
SELECT COUNT(A.InvNumber) AS NumberOfInvoices
,A.TotalSales
,MIN(A.TotalSales) AS MinimumSale
,MAX(A.TotalSales) AS LargestSale
,AVG(A.TotalSales) AS AverageSale
FROM (
SELECT
Lines.InvNumber
,SUM(Lines.line_price*Lines.line_units) AS TotalSales
FROM dbo.Lines INNER JOIN dbo.Invoices
ON Invoices.inv_number=Lines.inv_number
GROUP BY Lines.InvNumber
) A
You cannot select minimum on sum as SUM itself returns only one value... Also your syntax itself is not correct
I want to select the Total "sales" of a specific "main_category" for the year 2016
(main categories that don't have sales in that year should appear as zero)
I have managed to select the "sales" of a specific "main category" with all the other "main_categories" (that doesn't have any sales) appearing as zero using below query:
SELECT
mc.name,
ISNULL(SUM(s.no_of_units * b.unit_price),0) AS tCatSales
FROM Sales s
INNER JOIN Invoice i ON i.invoice_ID = s.invoice_id
INNER JOIN Inventory inv ON inv.inventory_ID = s.inventory_ID
INNER JOIN Batch b ON b.batch_ID = inv.batch_ID
INNER JOIN Products p ON p.product_id = b.product_ID
INNER JOIN Category c ON c.category_ID = p.category_id
RIGHT JOIN Main_Category mc ON mc.cat_id = c.main_category
--WHERE YEAR(i.trans_date) = 2016
GROUP BY mc.name
--HAVING YEAR(i.trans_date)=2016
but when I try to further segregate it for year 2016 ONLY either by WHERE clause or HAVING clause, it stops showing "main_category" names that have zero sales in the year.
One thing that I can think of is to give the query invoices only from 2016
which I tried to did by doing something like,
Replacing the line:
INNER JOIN Invoice i ON i.invoice_ID = s.invoice_id
with:
INNER JOIN Invoice i ON i.invoice_ID IN (SELECT invoice_id FROM Invoice in2 WHERE Year(in2.trans_date)=2016)
which did display the categories with zero values but with increased the calculated Sales Amount (from 2069 to something 203151022.75).
I understand this addition is somewhat illogical and disrupts the whole Inner Joins but so far these are the closest thing I can think of or find on the web.
I REPEAT the desired result is: main categories that don't have sales in that year should appear as zero with the year given year/month/date
As Sean and Eli mentioned, RIGHT JOIN is not recommended, you may change it to LEFT JOIN, OR use subquery like this:
SELECT
mc.name,
tCatSales = ISNULL(
(
SELECT
SUM(s.no_of_units * b.unit_price) AS tCatSales
FROM Sales s
INNER JOIN Invoice i ON i.invoice_ID = s.invoice_id
INNER JOIN Inventory inv ON inv.inventory_ID = s.inventory_ID
INNER JOIN Batch b ON b.batch_ID = inv.batch_ID
INNER JOIN Products p ON p.product_id = b.product_ID
INNER JOIN Category c ON c.category_ID = p.category_id
WHERE mc.cat_id = c.main_category
AND YEAR(i.trans_date) = 2016
) , 0)
FROM Main_Category mc
try this:
WHERE ISNULL(YEAR(i.trans_date), 1) = 2016
if you put simple equals conditions on outer join it will eliminate nulls, which give zero-valued rows you desire.
Also note that something like:
WHERE YEAR(i.trans_date) = 2016
is not sargable, see here
I have written a query
SELECT Year(outertblissues.opendt) AS Years,
Month(outertblissues.opendt) AS Months,
outertblvulnerability.vulname,
Count(outertblvulnerability.vulid) Vulcount
FROM tbl_apptestdetails AS outertblapptestdetails
INNER JOIN tbl_applicationlist AS outertblapplicationlist
ON outertblapptestdetails.appid = outertblapplicationlist.appid
INNER JOIN tbl_bu AS outertblbu
ON outertblbu.buid = outertblapplicationlist.buid
INNER JOIN tbl_issues AS outertblissues
ON outertblapptestdetails.testdetailid =
outertblissues.testdetailid
AND outertblissues.status NOT IN( '1', '4' )
INNER JOIN tbl_vulnerability AS outertblvulnerability
ON outertblissues.vulid = outertblvulnerability.vulid
GROUP BY Year(outertblissues.opendt),
Month(outertblissues.opendt),
outertblvulnerability.vulname
ORDER BY vulcount DESC
Which gives the following result
Now a want one more column Name as SumOfCount which gives the Sum of all VulCount Related to a particular VulName For example in front of "Additional Issues" The SumOfCount Should be 8 , Similarly for others
If you use Sql Server 2012 or higher you can try instruction Sum() over partition by
SUM(VulCount) OVER(PARTITION BY VulName)
I am retrieving data from table ProductionReportMetrics where I have column NetRate_QuoteID. Then to that result set I need to get Description column.
And in order to get a Description column, I need to join 3 tables:
NetRate_Quote_Insur_Quote
NetRate_Quote_Insur_Quote_Locat
NetRate_Quote_Insur_Quote_Locat_Liabi
But after that my premium is completely off.
What am I doing wrong here?
SELECT QLL.Description,
QLL.ClassCode,
prm.NetRate_QuoteID,
QL.LocationID,
ISNULL(SUM(premium),0) AS NetWrittenPremium,
MONTH(prm.EffectiveDate) AS EffMonth
FROM ProductionReportMetrics prm
LEFT JOIN NetRate_Quote_Insur_Quote Q
ON prm.NetRate_QuoteID = Q.QuoteID
INNER JOIN NetRate_Quote_Insur_Quote_Locat QL
ON Q.QuoteID = QL.QuoteID
INNER JOIN NetRate_Quote_Insur_Quote_Locat_Liabi QLL
ON QL.LocationID = QLL.LocationID
WHERE YEAR(prm.EffectiveDate) = 2016 AND
CompanyLine = 'Ironshore Insurance Company'
GROUP BY MONTH(prm.EffectiveDate),
QLL.Description,
QLL.ClassCode,
prm.NetRate_QuoteID,
QL.LocationID
I think the problem in this table:
What Am I missing in this Query?
select
ClassCode,
QLL.Description,
sum(Premium)
from ProductionReportMetrics prm
LEFT JOIN NetRate_Quote_Insur_Quote Q ON prm.NetRate_QuoteID = Q.QuoteID
LEFT JOIN NetRate_Quote_Insur_Quote_Locat QL ON Q.QuoteID = QL.QuoteID
LEFT JOIN
(SELECT * FROM NetRate_Quote_Insur_Quote_Locat_Liabi nqI
JOIN ( SELECT LocationID, MAX(ClassCode)
FROM NetRate_Quote_Insur_Quote_Locat_Liabi GROUP BY LocationID ) nqA
ON nqA.LocationID = nqI.LocationID ) QLL ON QLL.LocationID = QL.LocationID
where Year(prm.EffectiveDate) = 2016 AND CompanyLine = 'Ironshore Insurance Company'
GROUP BY Q.QuoteID,QL.QuoteID,QL.LocationID
Now it says
Msg 8156, Level 16, State 1, Line 14
The column 'LocationID' was specified multiple times for 'QLL'.
It looks like DVT basically hit on the answer. The only reason you would get different amounts(i.e. duplicated rows) as a result of a join is that one of the joined tables is not a 1:1 relationship with the primary table.
I would suggest you do a quick check against those tables, looking for table counts.
--this should be your baseline count
SELECT COUNT(*)
FROM ProductionReportMetrics
GROUP BY MONTH(prm.EffectiveDate),
prm.NetRate_QuoteID
--this will be a check against the first joined table.
SELECT COUNT(*)
FROM NetRate_Quote_Insur_Quote Q
WHERE QuoteID IN
(SELECT NetRate_QuoteID
FROM ProductionReportMetrics
GROUP BY MONTH(prm.EffectiveDate),
prm.NetRate_QuoteID)
Basically you will want to do a similar check against each of your joined tables. If any of the joined tables are part of the grouping statement, make sure they are also in the grouping of the count check statement. Also make sure to alter the WHERE clause of the check count statement to use the join clause columns you were using.
Once you find a table that returns the incorrect number of rows, you will have your answer as to what table is causing the problem. Then you will just have to decide how to limit that table down to distinct rows(some type of aggregation).
This advice is really just to show you how to QA this particular query. Break it up into the smallest possible parts. In this case, we know that it is a join that is causing the problem, so take it one join at a time until you find the offender.
SELECT TOP (100) PERCENT dbo.Travelers.InsDate,
dbo.Certificates.CertificateNumber,
dbo.Certificates.Payment,
dbo.Travelers.FirstName,
dbo.Travelers.LastName,
dbo.Travelers.DOB,
dbo.Travelers.Address,
dbo.Travelers.City,
dbo.Travelers.State,
dbo.Travelers.Zip,
dbo.Travelers.Email,
dbo.Travelers.BestPhone,
dbo.Buyers.Name,
dbo.Buyers.SalesRep,
dbo.Sales.BoxNumber
FROM dbo.Sales
INNER JOIN dbo.Buyers ON dbo.Sales.BuyerID = dbo.Buyers.ID
INNER JOIN dbo.Travelers
INNER JOIN dbo.Certificates ON dbo.Travelers.CertificateID = dbo.Certificates.ID ON dbo.Sales.BoxNumber = LEFT(dbo.Certificates.CertificateNumber, 4)
WHERE (dbo.Certificates.PaymentCode = '1')
ORDER BY dbo.Travelers.InsDate DESC
This query is returning multiple records with the same CertificateNumber. I want it to return a DISTINCT CertificateNumber but since the BoxNumber is a derivative of CertificaeNumber it is returning multiple rows.
I have tried Distinct and Group BY.
Any one have any suggestions?
Upon further research another issue was exposed, BoxNumbers were sold to multiple buyers. Once I fixed this issue it ran fine.