简体   繁体   中英

SQL Server query with sums from multiple tables

I have 3 tables that I am trying to report from that are all related but have a different number of records. I want a summary line for each order that shows job description, total price and total cost.

My tables are a follows:

Prices

| Order | Line # | Description  | Price |
+-------+--------+--------------+-------+
| 1     | 1      | Line 1 job#1 | 100   |
| 1     | 2      | Line 2 job#1 | 30    |
| 2     | 1      | Line 1 job#2 | 100   |
| 3     | 1      | Line 1 job#3 | 75    |

Cost lines

| Order | Line # | Cost record | Cost |
+-------+--------+-------------+------+
| 1     | 1      | 1           | 80   |
| 1     | 2      | 2           | 80   |
| 1     | 2      | 3           | 50   |
| 2     | 1      | 1           | 75   |
| 3     | 1      | 1           | 50   |
| 3     | 1      | 2           | 50   |

Order Header

| Order | Description | Sales Person |
+-------+-------------+--------------+
| 1     | Order # 1   | 1            |
| 1     | Order #2    | 2            |
| 1     | Order #3    | 1            |

I keep getting way to many associated rows. I've been trying subqueries with sums but I just can't get it to work.

Expected result:

 | Order | Description | Price | Cost | Sales Person |
 +-------+-------------+-------+------+--------------+
 | 1     | Order #1    | 130   | 210  | 1            | 
 | 2     | Order #2    | 100   | 75   | 2            |
 | 3     | Order #3    | 75    | 100  | 1            | 

I assume there is a mistake in your sample data and the first column should read 1 , 2 and 3 rather than three times 1 . At least your desired result makes that seem very plausible.

Join the costs and prices to the orders and then GROUP BY the orders and calculate the sum for the costs and prices.

 SELECT o.[Order],
        o.[Description],
        sum(p.[Price]) [Price],
        sum(c.[Cost]) [Cost],
        o.[Sales Person]
        FROM [Order Header] o
             LEFT JOIN [Cost lines] c
                       ON c.[Order] = o.[Order]
             LEFT JOIN [Prices] p
                       ON p.[Order] = o.[Order]
        GROUP BY o.[Order],
                 o.[Description],
                 o.[Sales Person];

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM