Choc
Choc

Reputation: 1

SELECT statement within a SELECT

I have the following T-sql code

SELECT DISTINCT
    DATEPART(DW, [DATE]) AS datepar,
    DATENAME(dw, [Date]) AS dy,
    EDEN = (SELECT SUM(total) AS UnusedTotal 
            FROM [dbo].[CHEA_CCG_Report] ccg  
            WHERE availability = 'Available' 
             AND [Name of the Location of the Session] in ('Cumberland Infirmary'))
FROM 
    [dbo].[CHEA_CCG_Report] ccg 

However, the code is returning the total of the sum against everyday. How would I reference it so that it brought back the sum just for that day?

Thanks

Upvotes: 0

Views: 77

Answers (2)

LukStorms
LukStorms

Reputation: 29647

Maybe a GROUP BY and use those conditions in the WHERE clause ?

(Untested)

SELECT
DATEPART(dw, [Date]) AS [datepar],
DATENAME(dw, [Date]) AS [dy],
SUM(total) AS EDEN
FROM [dbo].[CHEA_CCG_Report] AS ccg
WHERE availability = 'Available'
  AND [Name of the Location of the Session] IN ('Cumberland Infirmary')
GROUP BY DATEPART(dw, [Date]), DATENAME(dw, [Date])
ORDER BY [datepar], [dy]

Upvotes: 1

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

I would use APPLY :

SELECT DISTINCT DATEPART(DW, [DATE]) AS datepart, 
       DATENAME(dw, [Date]) AS dy, CCG1.UnusedTotal AS EDEN
FROM [dbo].[CHEA_CCG_Report] ccg OUTER APPLY
     (SELECT SUM(ccg1.total) AS UnusedTotal,  . . .  
      FROM [dbo].[CHEA_CCG_Report] ccg1
      WHERE ccg1.availability = 'Available' AND
            ccg1.[Name of the Location of the Session] IN ('Cumberland Infirmary') AND
            ccg.[DATE] = ccg1.[DATE]
     ) ccg1;

Assuming the [DATE] has DATE type only else you would need to do conversations.

Upvotes: 0

Related Questions