SELECT中的SELECT语句

时间:2018-10-12 16:39:01

标签: sql sql-server

我有以下T-sql代码

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 

但是,代码每天返回的总和。我将如何引用它,以便它带回当天的总和?

谢谢

2 个答案:

答案 0 :(得分:1)

也许是GROUP BY,并在WHERE子句中使用这些条件?

(未经测试)

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]

答案 1 :(得分:0)

我会使用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;

假设[DATE]仅具有DATE类型,否则您将需要进行对话。