Query To Return Sale Amount For Specified Employee

Below is my DDL - How can (in one query) I input an employee name and from the given employee name display all stores that were worked at and Total sale amounts per store for the specified employee?  Sample output would be
Store Name   Employee Name  Sale Amt
Two     afaslkfasd
100
Five      aslkjfla          300
Create Table StoreInfo
storeid int IDENTITY(1,1) PRIMARY KEY,
storename varchar(100),
employeeid int,
employee varchar(100)
Create Table SaleInfo
saleid int IDENTITY(1,1) PRIMARY KEY,
storeid int,
employeeid int not null,
saleamount int,
dateofsale SMALLDATETIME null
INSERT INTO StoreInfo VALUES
('One', 1, 'Mike Jones'),
('Two', 2, 'Lee Jones'),
('Three', 3, 'Fred Marx'),
('Four', 4, 'Lillard Halfling'),
('Five', 5, 'Joey Fratada'),
('Six', 6, 'Lethan James'),
('Seven', 7, 'Four-Finger Charlie'),
('Eight', 8, 'Twice Sold'),
('Nine', 9, 'Richard Jackson'),
('Ten', 10, 'Fred Mitch')
INSERT INTO SaleInfo VALUES
(1,1,452, '12-21-14'),
(1,1,452, '9-7-14' ),
(1,2,500, '12-7-14' ),
(1,3,100, '3-12-14' ),
(1,6,275, '12-2-14' ),
(1,7,800, '1-12-14' ),
(2,4,200, '2-16-14' ),
(2,5,110, '12-7-14' ),
(2,1,120, '8-12-14' ),
(2,3,320, '2-22-14' ),
(3,3,50, '3-12-14' ),
(3,1,75, '8-2-14' ),
(3,8,20, '7-12-14' ),
(3,9,42, '12-8-14' ),
(4,10,52, '12-16-14' ),
(4,1,152, '12-4-14'),
(4,8,452, '5-1-14'),
(4,7,752, '2-28-13' ),
(4,6,52, '1-22-14' ),
(4,2,42, '12-28-13' )

Thank you for trying to post the DDL we need to answer this. But you do not know RDBMS, or industry and ANSI/ISO standards in your data. You should learn ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal
data. Your choice of proprietary date format is literally the worst way to do it! Why do you think that IDENTITY has any place in RDBMS? Where were you when they discussed keys? You also have no idea what a normalized table is. An employee has a relationship
with a store; he is not an attribute of one! When you fire an employee, you destroy a store in your schema. 
Do people in your world have hundred letter names? The Post office uses 35 for an address line. If you invite garbage data, it will come. 
Why do you think that “_info” is a valid table name? Why are prices expressed in integers and not decimals? What currency on Earth is not decimal?
You need to read and download the PDF for: 
https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
Below is my DDL - How can (in one query) I input an employee name and from the given employee name display all stores that were worked at and Total sale amounts per store for the specified employee? 
Why don't you use DRI? That is what RDBMS is all about. 
CREATE TABLE Stores
(store_nbr CHAR(3) NOT NULL PRIMARY KEY
 CHECK (store_nbr LIKE '[0-9][0-9][0-9]'), 
 store_name VARCHAR(35) NOT NULL);
CREATE TABLE Personnel
(employee_id CHAR(10) NOT NULL PRIMARY KEY, 
 employee_name VARCHAR(35)NOT NULL);
Since we have no business rules, I will assume each employee is at one and one store, but a store can have many employees. 
CREATE TABLE Job_Assignments
(store_nbr CHAR(3) NOT NULL 
 REFERENCES Stores(store_nbr)
 employee_id CHAR(10) NOT NULL PRIMARY KEY
 REFERENCES Personnel (employee_id));
The sales tickets can be a CREATE SEQUENCE but let's skip that for now. I swill not re-copy your data into this valid schema, but you might want to do it to learn how. 
CREATE TABLE Sales
(sale_ticket INTEGER NOT NULL PRIMARY KEY,
 store_nbr CHAR(3) NOT NULL 
   REFERENCES Stores(store_nbr)
 employee_id CHAR(10) NOT NULL
   REFERENCES Personnel (employee_id), 
 sale_amount DECIMAL(12,2) NOT NULL, 
 sale_date DATE DEFAULT CURRENT_TIMESTAMP NOT NULL);
>> How can (in one query) I input an employee name and from the given employee name display all stores that were worked at and Total sale amounts per store for the specified employee?  <<
SELECT employee_name, store_name,
       SUM(T.sale_amount) AS sales_amt_tot
  FROM Sales AS T, Personnel AS P, Stores AS S
 WHERE P.employee_name = @in_employee_name
   AND T.employee_id = S.Employee_id 
   AND T.store_id = S.store_id 
 GROUP BY employee_name, store_name;
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL

Similar Messages

  • MDX Query for Average customer first sale amount for each year

    Hello,
    I new to MDX, and I am looking to build a query that would get all the first sale amount for the customes and average that.  The intent is to use find an average each year.   I am looking to use this against the adventure works database.   
    I am not sure exatcly how to start this .  Any help is much appreciated.
    J

    Hi,
    I'll do it in several stages.
    let's first define an ordered set of date/sale to one customer over all periods:
    SELECT
    {[Measures].[Internet Sales Amount]} ON 0
    NonEmpty
    [Date].[Calendar].[Date]
    [Customer].[Customer].&[15561]
    ,[Measures].[Internet Sales Amount]
    ,[Customer].[Customter].&[15561]
    ) ON 1
    FROM [Adventure Works];
    we retain the first line of the result set  with item(0):
    SELECT
    {[Measures].[Internet Sales Amount]} ON 0
    NonEmpty
    [Date].[Calendar].[Date]
    [Customer].[Customer].&[15561]
    ,[Measures].[Internet Sales Amount]
    ,[Customer].[Customer].&[15561]
    ).Item(0) ON 1
    FROM [Adventure Works];
    next, for each year we define a measure that will retain the first sale for each customer
    (I  limit the customer set to the first 2000)
    WITH
    MEMBER [Measures].[Mymeasure 2006] AS
    NonEmpty
    Exists
    [Date].[Calendar].[Date].MEMBERS
    ,[Date].[Calendar].[Calendar Year].&[2006]
    [Customer].[Customer].CurrentMember
    ,[Measures].[Internet Sales Amount]
    ,[Customer].[Customer].CurrentMember
    ).Item(0)
    ,[Measures].[Internet Sales Amount]
    MEMBER [Measures].[Mymeasure 2007] AS
    NonEmpty
    Exists
    [Date].[Calendar].[Date].MEMBERS
    ,[Date].[Calendar].[Calendar Year].&[2007]
    [Customer].[Customer].CurrentMember
    ,[Measures].[Internet Sales Amount]
    ,[Customer].[Customer].CurrentMember
    ).Item(0)
    ,[Measures].[Internet Sales Amount]
    SELECT
    [Measures].[Mymeasure 2006]
    ,[Measures].[Mymeasure 2007]
    } ON 0
    ,NON EMPTY
    Head
    [Customer].[Customer].[Customer]
    ,2000
    ) ON 1
    FROM [Adventure Works];
    We then take the average for each year:
    WITH
    MEMBER [Measures].[AVG cust first sale 2006] AS
    Avg
    Head
    [Customer].[Customer].[Customer]
    ,2000
    NonEmpty
    Exists
    [Date].[Calendar].[Date].MEMBERS
    ,[Date].[Calendar].[Calendar Year].&[2006]
    [Customer].[Customer].CurrentMember
    ,[Measures].[Internet Sales Amount]
    ,[Customer].[Customer].CurrentMember
    ).Item(0)
    ,[Measures].[Internet Sales Amount]
    MEMBER [Measures].[AVG cust first sale 2007] AS
    Avg
    Head
    [Customer].[Customer].[Customer]
    ,2000
    NonEmpty
    Exists
    [Date].[Calendar].[Date].MEMBERS
    ,[Date].[Calendar].[Calendar Year].&[2007]
    [Customer].[Customer].CurrentMember
    ,[Measures].[Internet Sales Amount]
    ,[Customer].[Customer].CurrentMember
    ).Item(0)
    ,[Measures].[Internet Sales Amount]
    SELECT
    [Measures].[AVG cust first sale 2006]
    ,[Measures].[AVG cust first sale 2007]
    } ON 0
    FROM [Adventure Works];
    Philip,

  • CPF contribution is not deducting on AWS amount for retried employee.

    Hi,
    Issue reported: - CPF contribution is not deducting on AWS amount for retried employee.
    fyi -even though employee is separated his bonus will be paid in month of December
    I have checked the AWS wage type, the culmination class 3 is checked, as it is an addition wage type.  And its 0185 and 0186 is not delimited also.
    How can I found out the root cause?
    Regards
    Thomas
    Edited by: Thomas Padiyara on Dec 9, 2010 2:49 AM

    Patch updates issue.

  • How do I determine the correct sales org for the employee?

    Hi
    The requirement here is to determine the correct sales org for the employee logged in when creating an activity (a customer visit). We know that all employees will belong to one sales org.
    On this basis, in the organisational data determination I have maintained the organisational data profile Z0001 with the Organisational Model Determination Rule: 10000162 (employees for responsible org. unit). I have left the Responsibilities Determination Rule empty. I am not sure if both have to be filled. Can anyone explain the difference between the two?
    I have checked the sales organisation and distribution channel. This is for the sales scenario.
    I simulated this rule in Maintain Determination Rules. I entered the Sales Org and no agents (employees) were found.
    The org data profile Z0001 has been assigned to the transaction.
    The Object Permitted in Determination has been checked for the sales scenario in the Organisational Model.
    Regards
    Declan

    Hi PePe
    I made the change and it worked as I wanted it. Thanks a lot.
    You say there's no need to Maintain the Responsibilities Rule. Can I ask what this section does and why it can be one or the other?
    Regards
    Declan

  • Query is returning multiple records for a bank account id and party id

    Hi All,
    I am not getting why this query is returning multiple records for a particular bank account id and party id:
    SELECT instrument_payment_use_id
    ,instrument_type
    ,instrument_id
    ,start_date
    ,ext_pmt_party_id
    FROM iby_pmt_instr_uses_all
    WHERE instrument_id =:lv_num_ext_bank_account_id
    and exists (select 1 from iby_external_payees_all b where PAYEE_PARTY_ID= :lv_num_party_id and b.ext_payee_id = ext_pmt_party_id)
    I want above values to be used in api iby_disbursement_setup_pub.set_payee_instr_assignment in R12.
    Please help asap.
    Thanks

    O/P of query run for
    SELECT rowid, instrument_payment_use_id
    FROM iby_pmt_instr_uses_all
    WHERE instrument_id =6642
    AND EXISTS (
    SELECT 1
    FROM iby_external_payees_all b
    WHERE payee_party_id= 85470
    AND b.ext_payee_id = ext_pmt_party_id);
    is below:
    Rowid     INSTRUMENT_PAYMENT_USE_ID
    AABiDXAGIAABhiKAAS     236586
    AABiDXAGRAABSjtAAz     148437
    The version is R12

  • A query to create sales information for a specific date.

    Hi,
    Please look at attached image, you will see how this query look like. This query will generate all sales from 1/1/2014 until today. I would like to see if the query can create the sales report for a range from 1/1/2014 until yesterday (does not included any sales for today). Any help will be appreciated.
    -Bill

    Hi Bill,
    The query attached looks like it is selecting results based on the salesorder name starting with the current year. As is written, it won't be able to filter out today.
    If you want to exclude today, you'll need to modify the current selectivity predicate for today to perhaps a BETWEEN predicate ( e.g. table.datefield BETWEEN '2014-01-01' and DATEADD(day,-1,GETDATE()) ) or add an exclusion predicate ( e.g. table.datefield <> DATEADD(day,-1,GETDATE()) ).
    Note that you'll need to have a field in the data that has the day. Your query does not have any schema information, and all it seemingly reveals is that a salesorder name starts with the current year.
    Hope this helps,
    Tyson

  • Returns sales document for cancelled invoice

    Dear SAP Gurus,
    User has created a normal invoice with certain finished goods. Due to some reasons he cancelled this invoice with T code VF11. And then he tried to create a returns order wrt original invoice and created returns sales document without any error.
    OR --> LF --> F2 --> S1 (Cancel invoice)
                          F2 ---> RE ?
    Is this the standard behavoiur of the system or...is there any problem in copy controls config from Invoice document to Sales document.
    Request you to please suggest me how to process further..
    Thanks & regards,
    Praveen

    > My original billing document is already cancelled and when copying from F2 to RE, want an error message to be poped up saying billing document already cancelled, you cannot create a returns sales order.
    My ques. is Why will you create return sales order wrt billing document (F2) when it is not cancelled ?
    In other words, you will create return order when there is problem with material. So, for that you have to cancel the billing doc. which you already have done.
    So, when you create return order, you want the material to be entered in return order. So, you can use either original sales order or billing doc. (F2) as reference so that you need not enter all the items again in return order. You can also configure return order so that it will not take any reference while creation.
    In short, while creating return order you need to cancel the billing doc (F2) if it is there, so that all the accounting entries will be reversed and then have to create return order with ref to this billing doc. or original sales order.
    Hope you get some idea. Correct me if i am wrong anywhere
    regards,
    Sagar

  • What could be the query to get Spend Amount for a Product name in EBS?

    Hi Experts,
    I need a help to write a query in EBS to get Spend Amount for any given Product Name and Top Level Category (Segment1).
    It can be two different query or a single one. Please reply if anyone knows how to do it. I need it for testing purpose.
    Thanks in advance.

    All good here Sudipta.
    You can try the below SQL.
    SELECT msib.description,mcb.segment1,SUM(pla.quantity*pla.unit_price) total_spend
    FROM
    po_lines_all pla,
    mtl_categories_b mcb,
    mtl_system_items_b msib
    WHERE pla.category_id = mcb.category_id
    AND pla.item_id = msib.inventory_item_id
    AND msib.organization_id = <enter your item master organization id>
    GROUP BY msib.description,mcb.segment1
    If you don't want to use the PO_LINES_ALL, is there any other sourced you are planning to use for spend.
    SELECT mcb.segment1,SUM(pla.quantity*pla.unit_price) total_spend
    FROM
    po_lines_all pla,
    mtl_categories_b mcb
    WHERE pla.category_id = mcb.category_id
    GROUP BY mcb.segment1
    and do not need the po_lines_all table. I'm doing a data validation between OBIEE reports and EBS test data. In report i'm keeping only Product Name and Spend Amount to make it simple. Now I need to check the values are same in report and EBS. Thats the criteria.
    Thanks
    Sudipta

  • Sales office for an employee is displayed wrong for an activity.

    Hello,
    I am facing problem in Activity Moniter.
      An activity is maintained in the Tcode CRM_BUS2000126.So while monitering that activity through Activity moniter ,the Sales office for that particular employee is shown wrong and this sales office is not at all needed .
    So can i delete it.
    If I delete it will there be any problem .
    OR
    where can I make changes for Sales office if the sales of is wrong.
    Hint:In our Org structure the one userid is assigned to more than 2 Sales office.
    So please say whether this may be the problem or not.
    Regards,
    divya.

    As said in the preceding reply, if the status of the document is in simulation then you can delete else if it has been created, then document reversal needs to be done by selecting that particular document ID.

  • Query to return separate rows for date range including NULLs

    I'm trying to write a query that will return all customers from table 1. Table 1 also provides a start date and an end date that may be different for different customers. Left join with Table 2  provides all matches and NULL if NO matches.
    If there is any match at all, I do not get the NULLs for other dates. There should be a match for each date from start to end. How can I write the code so that my return will loop thru each date and provide the match or NULL?

    Sorry. I am somewhat new to this and am not sure what you are requesting. I receive a return of all customers with the code below but if customer 1 has a start date of 1/1/15 and a stop date of 1/5/15 and a document exists for 1/1/15 and 1/3/15
    I do not receive the rows with NUL for 1/2/15, 1/4/15, and 1/5/15 which is what I'm trying to accomplish. If there is no match at all, I only receive the one row with NULL and I would like to see a row for each date from start to stop.
    SELECT  T1.IDNumber,T1.StartDate,T1.StopDate,T3.SignDateTime
    FROM
    Table1 T1
    INNER
    JOIN Table2
    T2
    ON
    T1.CustID
    = T2.CustID
    LEFT
    JOIN Table3
    T3
    ON
    T1.CustID
    = T3.CustID
    WHERE
    T1.StartDate
    > '2015-01-20 00:00:00.000'
    AND
    (T3.ReportID
    IN ('DOC1',
    'DOC2',
    'DOC3') OR
    T3.ReportID
    IS NULL)
    AND
    T2.YesNo
    = 'Y'

  • OAB query to pull all dependents for an employee

    Hi ,
    I tried to query this view in Oracle OAB 'BEN_CVRD_DPNT_CTFN_PRVDD_V' but it does not have any data, I need to run a report which includes only the dependents with covered flag checked on designate dependent tabe on OAB screen.
    select distinct
    TO_CHAR(sysdate, 'MM/DD/YYYY') RUN_DATE
    ,TO_CHAR(sysdate + 31, 'MM/DD/YYYY') AS_OF_DATE
    ,per2.employee_number employee_number
    ,per2.national_identifier EE_SSN
    ,per2.person_id person_id
    , per2.full_name EE_name
    , substr(plan.name,1,30) plan_name
    , substr(opt.name, 1,30) option_name
    , to_char(prtt.enrt_cvg_strt_dt,'MM/DD/YYYY') emp_enrt_dt
    , per.national_identifier dpnt_SSN
    , per.employee_number dpnt_employee_number
    , per.full_name dpnt_name
    , to_char(dpnt.cvg_strt_dt,'MM/DD/YYYY') dpnt_enrt_dt
    ,per.person_id dpnt_person_id
    FROM ben.BEN_PRTT_ENRT_RSLT_F prtt
    , ben.ben_elig_cvrd_dpnt_f dpnt
    , apps.per_all_people_f per
    , apps.per_all_people_f per2
    , ben.ben_pl_f plan
    , ben.ben_oipl_f oipl
    , ben.ben_opt_f opt
    where prtt.person_id = per2.person_id
    and prtt.pl_id = plan.pl_id
    and NVL(prtt.oipl_id,-99) = oipl.oipl_id (+)
    and prtt.prtt_enrt_rslt_id = dpnt.prtt_enrt_rslt_id
    --- and prtt.per_in_ler_id = dpnt.per_in_ler_id
    and dpnt.dpnt_person_id = per.person_id
    and oipl.opt_id = opt.opt_id (+)
    and to_date(sysdate + 31) between prtt.effective_start_date and prtt.effective_end_date
    AND to_date(sysdate + 31) between prtt.enrt_cvg_strt_dt and prtt.enrt_cvg_thru_dt
    and to_date(sysdate + 31) between dpnt.effective_start_date(+) and dpnt.effective_end_date(+)
    and to_date(sysdate + 31) between dpnt.cvg_strt_dt(+) and dpnt.cvg_thru_dt(+)
    and to_date(sysdate + 31) between per.effective_start_date(+) and per.effective_end_date(+)
    and to_date(sysdate + 31) between per2.effective_start_date(+) and per2.effective_end_date(+)
    and to_date(sysdate + 31) between plan.effective_start_date(+) and plan.effective_end_date(+)
    and to_date(sysdate + 31) between oipl.effective_start_date(+) and oipl.effective_end_date(+)
    and prtt.prtt_enrt_rslt_stat_cd is null
    ORDER BY per2.national_identifier, substr(plan.name,1,30)
    Please advice.
    Regards,
    AJ
    Edited by: 874127 on Sep 22, 2011 9:29 AM

    Can you also post the query for people who read this post and are also looking for an answer?
    Regards,
    Johan Louwers.

  • Standard SAP Report to get Manager PERNRs for specified Employee PERNRs

    Hello All,
    Is there any standard report whcih I can use to pass Employee PERNRs in the selection, and get the respective Manager PERNRs as output?
    Thanks,
    NS

    Nakul,
    For you information, PA and OM is be organized in the O-S-P(organization-position-person)  format
    There is no direct relationship between the employee to employee. It is like
    Employee to Employee position
    Then position to position (A002 - Reporting line)
    Then position to employee (Reporting Manager).
    For any coding part Check this link
    Re: Getting reporting data of all pernrs
    Regards,
    Anand babu R

  • Sales Commission Report for All Employees

    I'm trying to make a couple smartforms that will do the following tasks (each task is a separate smartform):
    1. Display the total sales amount for ALL employees over one month in a table format
    2. Display the total sales amount and commission for ONE employee over one month
    From my understanding, the way this can be achieved is through the ICM module?  I don't believe there are any default smartforms or sapscripts that are available for this functionality.  Can you please post information or links on how I would do this.
    I am also wondering if I will have to create a function module to create this form, or if I can use a print preview after setting the output type for this type of application?

    Try transaction VA05. In that choose "Open Orders" along with other selection criteria.
    If you want the Open sales order qty in output and its not displayed, do the following.
    Sales -> System modification -> create new fields ( without condition technique) -> New fields for lists.
    You can change V05TZZMO and structure VBMTVZ from there or use SE38 / SE11.
    For both you'll need an object registration in OSS.
    Hope this helps.
    Thanks,
    Balaji

  • ATP Check against customer stock for return Sale order

    Hi Friends,
    Pl.help in this.
    1. Is it possible to configure ATP check against Customer stock in a Sale order/Return order/any other way? ( Actuallly, client wants to take back empty cylinders through return sale order by ATP check against the customer stock)
    Regards,
    Mani

    Hi Mani ,
    Are you  taking cylinder as returable packing item or not?
    ex- For soft  drinks or beverages industry  it pretty common , they  use thel returnable package material type and more over why you want  use return sales order for this?
    Note- Just plz explain  scenario to MM and PP People also as availability check with all combination
    Hope it is helpful to you,
    Regards
    Venkat

  • Error while inbound creation for return sales order

    Hi all,
             We are in the process of creating return sales order for invoice cancelation.
             We have created return sales order.
             we have made settings for automatic inbound creation.
             While creating inbound delivery system giving following error,
    <b>Material cannot be used for inbound delivery because QM is active.</b>
    Please help in solving error.
    regards,
    Mona

    dear  kiran,
                        Tcode is for job planning,where can i make the required setting.
                        Can you explain in detail?
    regards,
    Mona

Maybe you are looking for

  • Will not boot AHT

    I have a 2002 model dual-867MHz Mirrored Drive Door Mac, which started locking up for no apparent reason after a certain amount of time. I took the logical step of downloading and burning the Apple Hardware Test CD for my Mac, and when I went into St

  • Cannot drop cube or analytic workspace due to ORA-37409

    The error is ORA-37409: cannot delete or truncate AW used by CUBE ORGANIZED table. This seems very closely related to the bug discussed in this thread: Drop cube organized table We need to drop and rebuild a cube due to a design change. It looks like

  • Lightroom mobile

    I bought Lightroom (not through Creative Cloud), i.e. I paid for the software outright.  I also have an adobe ID.  I thought that if I owned the software outright and had an adobe ID I could use Lightroom mobile.  However I have downloaded the app bu

  • Display format page by page

    hi In my program resultset contain more than 30 records. I want to display 20 records and first page contain 10 records and second page contain 10 records. The results should be shown in two pages with the index Page 1 of 1 or Page 1 of 2. Suppose If

  • Previous year arrear

    Hi Experts, CLIENT IS USING LEGACY SYSTEM CURRENTLY. Currently the client is having FY from Feb - Mar. Now they are planning to streamline there process with standard and make FY from Apr - Mar. Now for FY 2007 employee has paid ITax upto Feb. In FY