[英]SELECT statement within a SELECT
I have the following T-sql code 我有以下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
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 ? 也许是
GROUP BY
并在WHERE
子句中使用这些条件?
(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
: 我会使用
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. 假设
[DATE]
仅具有DATE
类型,则您需要进行对话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.