Sum of All Total related to a Vulnerability Name - sql-server

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)

Related

Extract Specific Data After a aggregation (Or any other solution for the desired result)

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

IN clause not working within subquery inner join

I am trying to pull a list of most recent lab values in 2015. All lab value are stored in one table and I need to both limit the data to be within 2015 and limit it to certain types of labs so the max date doesn't give me the most recent lab regardless of type. Although I use the IN clause, labs of other types are included. I need the last value regardless of what type of lab they have as long as it's within the types identified in the IN clause (i.e. I don't need the last value of each type)
select distinct
t2.pat_id
,t2.pat_last_name "PatientLast"
,t2.pat_first_name "PatFirst"
,t2.birth_date
,t1.contact_date "ContactDate"
,t3.name "EncounterType"
,t4.ord_num_value "Numeric Value"
,t4.result_date
from table1 t1
inner join table2 t2 on t1.pat_id = t2.pat_id
inner join table3 t3 on t1.enc_type_c = t3.disp_enc_type_c
inner join table4 t4 on t1.pat_enc_csn_id = t4.pat_enc_csn_id
inner join
(
select
table1.pat_id
,max(table1.contact_date) as LastResult
,table4.component_id
from table1
**inner join order_results on table1.pat_enc_csn_id = table4.pat_enc_csn_id
where table4.component_id in ('1526664','1558024','1004','2667', '1230000002','1564041')
and table1.contact_date between '2015-01-01' and '2015-12-31'
group by table1.pat_id, table4.component_id
) enc2** on table1.pat_id = enc2.pat_id
and table1.contact_date = enc2.LastResult
order by table2.pat_last_name, table2.pat_first_name
Your query is a bit hard to follow. But one method is to use row_number(). Something like this:
select t.*
from (select . . .,
row_number() over (partition by pat_id order by contact_date desc) as seqnum
from . . .
where . . .
) t
where seqnum = 1;
You have where conditions in the subquery that are not in the outer query, so it is hard to follow the intended logic. The use of row_number() is much simpler than a subquery, because you don't have to repeat any logic.

SQL: Select a column independent of where clause

SELECT TOP 1000 p.Title,p.Distributor, SUM(r.SalesVolume) AS VolumeOfSales,
CAST(SUM(r.CustomerPrice*r.SalesVolume) as decimal (18,0)) AS ValueOfSales,
CAST (AVG(r.CustomerPrice) as decimal (18,1)) AS AvgPrice,
p.MS_ContentType AS category ,Min(c.WeekId) AS ReleaseWeek
from Product p
INNER JOIN RawData r
ON p.ProductId = r.ProductId
INNER JOIN Calendar c
ON r.DayId = c.DayId
WHERE c.WeekId BETWEEN ('20145231') AND ('20145252')
AND p.Distributor IN ('WARNER', 'TF1', 'GAUMONT')
AND p.VODEST IN ('VOD', 'EST')
AND p.ContentFlavor IN ('SD', 'HD', 'NC')
AND p.MS_ExternalID1 IN ('ADVENTURE/ACTION', 'ANIMATION/FAMILY', 'COMEDY')
AND p.MS_ContentType IN ('FILM', 'TV', 'OTHERS')
AND r.CountryId = 1
GROUP BY p.Title,p.Distributor,p.MS_ContentType
ORDER BY VolumeOfSales DESC, ValueOfSales DESC
I want to madify the above query so that only the column ReleaseWeek is independent of the where clause WHERE c.WeekId BETWEEN ('20145231') AND ('20145252')
The result that I dervive looks like:
`Title Distributor VolumeOfSales ValueOfSales AvgPrice category ReleaseWeek
Divergente M6SND 94038 450095 4.0 Film 20145233`
However what I really want is the ReleaseWeek to be the first value in the column c.WeekId corresponding to that Titlein the database and not the first one between ('20145231') AND ('20145252') What is the best way to modify it? Any leads would be greatful.

Count by group as part of a SQL Server query

I have the following SQL server query:
SELECT G.StyleID,
G.Size, Count(*) As 'Count',
G.PropertyID FROM TBL_Garment G
LEFT OUTER JOIN TBL_EmployeeJob ON TBL_EmployeeJob.ID = G.EmployeeJobID
LEFT OUTER JOIN TBL_DepartmentJob ON TBL_DepartmentJob.ID = TBL_EmployeeJob.DepartmentJobID
LEFT OUTER JOIN TBL_Department ON TBL_Department.ID = TBL_DepartmentJob.DepartmentID
LEFT OUTER JOIN TBL_Division ON TBL_Division.ID = TBL_Department.DivisionID
LEFT OUTER JOIN TBL_Job ON TBL_Job.ID = TBL_DepartmentJob.JobID
WHERE G.EmployeejobiD IS NOT NULL
AND TBL_Division.ID = N'1'
AND TBL_Department.ID = N'1'
AND TBL_Job.ID = N'1'
AND G.PropertyID = 1
GROUP BY G.StyleID, G.Size, G.PropertyID
ORDER BY G.StyleID
and here are the results returned by this query:
Now I need 2 extra columns in this table:
One is the sum of the count by StyleID (As Total), and the other is Count/Total.
I am sure I can get the count/Total on my own, but do not know how to get the Total column, or even if it is possible.
Below is a version of how I would like the table to be:
You can use a windowing function:
sum([Count]) over (partition by [StyleID])
Make sure it's good enough for you performance-wise, though.

Group by in SQL Server

I have a query in SQL Server
SELECT
k12_dms_contacts_master.prefix_id AS prefix,
k12_dms_contacts_master.first_name,
k12_dms_contacts_master.last_name,
k12_dms_contacts_master.email,
k12_dms_institution_master.inst_name,
k12_dms_institution_master.address,
k12_dms_cities.name AS city_name,
k12_dms_zip_codes.zip_code,
k12_dms_institution_master.type_id,
k12_dms_contacts_institution_jobtitles.glevel_id,
k12_dms_districts.name AS district_name,
k12_dms_counties.name AS county_name,
k12_dms_institution_master.state_id,
k12_dms_institution_master.phone,
k12_dms_contacts_institution_jobtitles.job_title_id
FROM
k12_dms_institution_master
INNER JOIN k12_dms_contacts_institution_jobtitles ON k12_dms_contacts_institution_jobtitles.inst_id = k12_dms_institution_master.id
INNER JOIN k12_dms_contacts_master ON k12_dms_contacts_institution_jobtitles.contact_id = k12_dms_contacts_master.id
INNER JOIN k12_dms_cities ON k12_dms_cities.id = k12_dms_institution_master.city_id
INNER JOIN k12_dms_districts ON k12_dms_districts.id = k12_dms_institution_master.district_id
INNER JOIN k12_dms_counties ON k12_dms_counties.id = k12_dms_institution_master.county_id
INNER JOIN k12_dms_zip_codes ON k12_dms_zip_codes.id = k12_dms_institution_master.zip_code_id
WHERE
k12_dms_zip_codes.zip_code IN ('92678', '92679', '92688', '92690', '92691', '92692', '92693', '92694', '92877',
'92879', '92881', '92883')
ORDER BY
k12_dms_institution_master.state_id,
k12_dms_institution_master.inst_name ASC
Now I want to perform GROUP BY on Email address and Institution name but I am getting this error :
Column 'k12_dms_contacts_master.prefix_id' is invalid in the select
list because it is not contained in either an aggregate function or
the GROUP BY clause.
Any help would be highly appreciable.
The error message says it all.
You have created a group and since this column is not part of the "group by" nor an aggregation of all the groups column (like sum or count) you can't use it in the select clause.
Please note that the return of a group by is one row per group. Logically, that column would be different for any group member so it can not fit one line!

Resources