2

I have two SQL queries that I'm running from a C# winform, and I want to merge them.

The first is:

SELECT * FROM ES_TOOL INNER JOIN ES_HARDWARE ON ES_HARDWARE.eshw_ID = ES_TOOL.ESTOOL_HARDWARE 
                INNER JOIN ES_PAYMENT on ES_payment.espay_id = es_TOOL.estool_payment

This gives a list of all the tools and their associated payment and hardware requirements.

And the second is run on each record that the first query returns, by means of a c# for loop:

SELECT avg(a.esmrk_value) from ES_MARK a Inner Join ES_TOOL_CHAPTER b 
on  a.esmark_tool_chapter= b.estch_id WHERE b.estch_tool=@tool

This returns, for each tool, the average grade they've been awarded in the es_mark table.

N.B. Marks are awarded for individual "chapters" of tools. So, to find all the marks for a tool we need to see the ES_TOOL_CHAPTER table for a list of tool-chapters. Tool-chapters are what receive marks in the ES_MARK table.

I've tried grouping and more joins, but I'm just getting more confused by the minute, so I'd appreciate any help on the matter. I'm basically looking for one query that will return all the results of the first query with an additional column for average mark.

Thanks.

Edit: the @tool represents the tool id.

Meir
  • 12,285
  • 19
  • 58
  • 70

1 Answers1

3

If you want to retrieve the average grade's together with the main query:

SELECT *
FROM ES_TOOL
  INNER JOIN ES_HARDWARE ON ES_HARDWARE.eshw_ID = ES_TOOL.ESTOOL_HARDWARE 
  INNER JOIN ES_PAYMENT on ES_payment.espay_id = es_TOOL.estool_payment
  LEFT JOIN (
    SELECT b.estch_tool, avg(a.esmrk_value) AvgValue
    FROM ES_MARK a
      Inner Join ES_TOOL_CHAPTER b 
        ON a.esmark_tool_chapter = b.estch_id
    GROUP BY b.estch_tool
  ) g ON ES_TOOL.ToolColumn =  g.estch_tool

Replace ToolColumn with the correct column name.

Note: SELECT * is not recommended, please read This question.

Community
  • 1
  • 1
The Scrum Meister
  • 29,681
  • 8
  • 66
  • 64