Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by in subquery and base query sql server

I want to know if the following is possible.

I have one table of which I want to retrieve 3 columns of data:

Day, Sum of hours worked, Sum of hours worked with condition

My query is

SELECT     Day, SUM(Regular + Extra + Overtime) AS [Potential Hours],
                      (SELECT     SUM(Extra + Regular + Overtime) AS Expr1
                        FROM          dbo.TICPlus_Effort_Billable_Only
                        WHERE      (Manager NOT LIKE '%manager1%')) AS [Billed Hours]
FROM         Billable AS Billable1
GROUP BY Day

With this query I get the sum of all the data in the subquery for each row, but I would like to have the subquery that includes the constraint to be grouped by day. Is it possible to have a group by in the subquery to do this so I get the daily sum with condition on a daily basis?

like image 404
Node17 Avatar asked Dec 23 '10 12:12

Node17


People also ask

Can you use GROUP BY in subquery?

You can use group by in a subquery, but your syntax is off.

Can we use ORDER BY and GROUP BY in same query?

Both GROUP BY and ORDER BY are clauses (or statements) that serve similar functions; that is to sort query results. However, each of these serve very different purposes; so different in fact, that they can be employed separately or together.

Can CTE be used in subquery?

¶ A CTE (common table expression) is a named subquery defined in a WITH clause. You can think of the CTE as a temporary view for use in the statement that defines the CTE. The CTE defines the temporary view's name, an optional list of column names, and a query expression (i.e. a SELECT statement).

Can a subquery be multi valued?

A multi-value subquery retrieves more than one value and has two forms of syntax, as shown below.


1 Answers

No, you will not be able to do that as the SUB QUERY in the SELECT list will then return more that 1 Value.

You need to do it in a SUB Query in the FROM clause

Something like

 SELECT Day, 
        SUM(Regular + Extra + Overtime) AS [Potential Hours],
        SubSum AS [Billed Hours]
FROM    Billable AS Billable1 LEFT JOIN
        (
            SELECT  Day,
                    SUM(Extra + Regular + Overtime) AS SubSum
            FROM    dbo.TICPlus_Effort_Billable_Only
            WHERE   (Manager NOT LIKE '%manager1%')
            GROUP BY Day
        ) s ON  Billable1.Day = s.Day
GROUP BY    Day
like image 77
Adriaan Stander Avatar answered Sep 20 '22 13:09

Adriaan Stander