开发者

SQL Query With Nested Sum

I am having to write quite a complicated query at the moment but I am getting stuck. The table structure is as follows

SQL Query With Nested Sum

Inquiry is linked to Timelog by a field called Inquiry_ID. My current code which brings back total minutes but for the entire table and not开发者_如何学JAVA per company. What I am basically after:

Two Columns one for company name (dbo.inquiry.concom) and another for total minutes. The table INQUIRY holds say 100 entries for the same company, I want a row to return the company name once and the total amount of minutes counted for that company name from TIMELOG.LOGMINS

So for example there are 50 entries in dbo.inquiry that have the same company name, I want it to display a distinct company but I need it to total the amount of minutes that is in another table. I am completely lost!

DECLARE @StartDate DATETIME, @EndDate DATETIME
SET              @StartDate = dateadd(mm, - 1, getdate())
SET              @StartDate = dateadd(dd, datepart(dd, getdate()) * - 1, @StartDate)
SET              @EndDate = dateadd(mm, 1, @StartDate)
SELECT DISTINCT TOP 100 PERCENT dbo.INQUIRY.CONCOM, TIMELOG_1.LOGMINS, dbo.INQUIRY.ESCDATE,  dbo.INQUIRY.INQUIRY_ID,
                                                  (SELECT     SUM(LOGMINS) AS Expr1
                                                    FROM          dbo.TIMELOG
                                                    WHERE      dbo.INQUIRY.ESCDATE BETWEEN @Startdate AND @EndDate) AS TOTALMINUTES
                       FROM         dbo.INQUIRY INNER JOIN
                                              dbo.TIMELOG AS TIMELOG_1 ON dbo.INQUIRY.INQUIRY_ID = TIMELOG_1.INQUIRY_ID INNER JOIN
                                              dbo.PROD ON dbo.INQUIRY.PROD_ID = dbo.PROD.PROD_ID INNER JOIN
                                              dbo.CATEGORY ON dbo.PROD.CATEGORY_ID = dbo.CATEGORY.CATEGORY_ID
                       WHERE     dbo.INQUIRY.ESCDATE BETWEEN @Startdate AND @EndDate
                       ORDER BY dbo.INQUIRY.CONCOM

EDIT: The reason the category and product tables are there is because I will need to exclude the count based on whether a product is in a certain category.


SELECT  i.concom, COALESCE(SUM(t.logmins), 0)
FROM    inquiry i
LEFT JOIN
        timelog t
ON      t.inquiry_id = i.inquiry_id
GROUP BY
        i.concom
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜