Home > Database > Mysql Tutorial > How to Get the First Workflow for Each Sales Representative in SQL?

How to Get the First Workflow for Each Sales Representative in SQL?

Patricia Arquette
Release: 2025-01-22 06:16:08
Original
748 people have browsed it

How to Get the First Workflow for Each Sales Representative in SQL?

Get the first workflow for each sales rep from SQL database

This article explores how to retrieve the first row of data for each sales representative from the database table, focusing on the situation where there are multiple workflows for each representative, with the goal of obtaining the initial workflow for this month and this year.

For this we can use the ROW_NUMBER() function as shown below:

<code class="language-sql">SELECT *
FROM (
    SELECT 
        workflowid, 
        salesRepId, 
        quantityAssigned,
        quantityLeft, 
        month, 
        year,
        ROW_NUMBER() OVER (PARTITION BY salesRepId ORDER BY workflowid) AS rownumber
    FROM sm_salesRepWorkflow
) AS RankedWorkflows
WHERE rownumber = 1;</code>
Copy after login

This query first assigns a row number to each workflow record by sales representative ID. Subsequently, it selects only records with row number equal to 1.

Example usage

Consider the following data:

workflowid salesRepId quantityAssigned quantityLeft month year
WF_101 EMP_101 100 90 May 2013
WF_101 EMP_102 100 100 May 2013
WF_101 EMP_103 100 80 May 2013
WF_102 EMP_101 100 70 May 2013

Executing the query will retrieve the following results:

workflowid salesRepId quantityAssigned quantityLeft month year
WF_101 EMP_101 100 90 May 2013
WF_101 EMP_102 100 100 May 2013
WF_101 EMP_103 100 80 May 2013

These rows represent the first workflow for each representative in the specified month and year. Note that the ordering of workflowid determines the "first" workflow. If you need to determine the first workflow based on other columns (such as date), you need to adjust the ORDER BY clause.

The above is the detailed content of How to Get the First Workflow for Each Sales Representative in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template