I have a procedure that outputs a list of rows with your standard basic SELECT
statement using a few joins
and where
clauses.
Employee Value
--------------------------
Tommy Elliott Damage
Tommy Elliott Overage
Tommy Elliott Damage
Tommy Elliott Shortage
Tommy Elliott Damage
Tommy Elliott Shortage
Trevor Gray Overage
Trevor Gray Shortage
Trevor Gray Overage
Trevor Gray Shortage
Trevor Gray Overage
Trevor Gray Shortage
I am wondering if anyone would know of a solution where I can either add a new SELECT statement below this one or within the same SELECT statement that would be able to:
count the number of times Tommy and Trevor appear (which should be six based on the data above)
and for Tommy and Trevor, count the number of times they have a value of damage, overage, or shortage.
I've been trying to figure it out and can't. I'm sure there's a quick solution to COUNT
.
The analytic version of COUNT()
can add these as column values and preserve the detail you want. Assuming your query starts like this:
SELECT
Employee,
Value
FROM ... and the rest of your query
... add the counts like this:
SELECT
Employee,
Value,
COUNT(*) OVER (PARTITION BY Employee) AS ThisEmpCount,
COUNT(CASE WHEN Value = 'Damage' THEN 1 END)
OVER (PARTITION BY Employee) AS ThisEmpDamageCount,
COUNT(CASE WHEN Value = 'Outage' THEN 1 END)
OVER (PARTITION BY Employee) AS ThisEmpOutageCount
FROM ... and the rest of your query
select T.Employee, COUNT(T.Employee)
from
(
your query
)T
group by T.Employee
SELECT Employee, Value, Count(1) as No_Of_Times
FROM [Table]
GROUP BY Employee, Value
ORDER BY Employee, Value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.