SQL query result monthly arrangement

2019-08-18 22:16发布

问题:

I have two tables

(1) MonthlyTarget {SalesManCode, TargetValue};

(2) MonthlySales  {SalesManCode, SaleDate, AchievedValue};

I have to make a query that produces a result like the following table:

{SalesManCode, JanTar, JanAch, FebTar, FebAch,....., DecTar, DecAch}

What should be the query?

回答1:

What database are you using? I have a stored procedure that simplifies doing that type of pivot for Microsoft SQL Server 2005 ...

If you are using SQL Server 2005:

Run this to install the pivot_query procedure.

Here is an example like you described, the output looks like:

SalesManCode April_Tar    April_Ach    February_Tar February_Ach January_Tar  January_Ach  March_Tar    March_Ach    
------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ ------------ 
Bob          12000.000    9000.000     9000.000     9000.000     10000.000    11000.000    11000.000    10000.000    
Sara         12000.000    9200.000     9000.000     9300.000     10000.000    11500.000    11000.000    10200.000