简体   繁体   中英

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

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]

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.

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