我有3个SQL语句,我想创建一个视图并返回3列,每列代表一个计数。
以下是我的陈述
SELECT Count(*)
FROM PlaceEvents
WHERE PlaceID = {placeID} AND EndDateTimeUTC >= GETUTCDATE()
SELECT Count(*)
FROM PlaceAnnouncements
WHERE PlaceID = {placeID}
SELECT Count(*)
FROM PlaceFeedback
WHERE PlaceID = {placeID} AND IsSystem = 0
我知道如何创建一个基本视图但是如何创建一个允许我将这3个列placeID
作为用于过滤的列
我想执行以下操作以返回正确的数据
SELECT *
FROM vMyCountView
WHERE PlaceID = 1
CREATE VIEW vMyCountView AS
(...) AS ActiveEvents,
(...) AS Announcements,
(...) AS UserFeedback,
PlaceID
答案 0 :(得分:1)
我宁愿使用一个函数,然后使用一个视图:
这允许您传入您喜欢的任何参数(我假设placeId是INT)并在您的查询中处理它。处理非常简单,只需使用View:
Name: ABC,
Department: Technical
Salary: 1000
Name: XYZ
Department: Technical
Salary: 1200
Name: PQR
Department: Technical
Salary: 1600
这就是你怎么称呼它。您可以将其用于CREATE FUNCTION MyCountFunction(@PlaceID INT)
RETURNS TABLE
AS
RETURN
SELECT
(SELECT Count(*) FROM PlaceEvents WHERE PlaceID = @PlaceID AND EndDateTimeUTC >= GETUTCDATE()) AS ActiveEvents
,(SELECT Count(*) FROM PlaceAnnouncements WHERE PlaceID = @PlaceID) AS Announcements
,(SELECT Count(*) FROM PlaceFeedback WHERE PlaceID = @PlaceID AND IsSystem = 0) AS UserFeedback
,@PlaceID AS PlaceID;
GO
s或JOIN
也...
APPLY
答案 1 :(得分:0)
您可以将它们组合为多个选择子查询。
CREATE VIEW vMyCountView AS
SELECT
(SELECT Count(*) FROM PlaceEvents
WHERE PlaceID = s.placeID AND EndDateTimeUTC >= GETUTCDATE()) AS ActiveEvents,
(SELECT Count(*) FROM PlaceAnnouncements
WHERE PlaceID = s.placeID) AS Announcements,
(SELECT Count(*) FROM PlaceFeedback
WHERE PlaceID = s.placeID AND IsSystem = 0) AS UserFeedback,
placeID
from Sometable s
答案 2 :(得分:0)
根据定义,view
是一个select语句。如果对您的业务逻辑有意义,则可以使用join
,union
等提供 create view
是批量中唯一的查询。
答案 3 :(得分:0)
您可以使用GROUP BY
创建类似的视图:
SELECT
PlaceId
, Count(peId) AS ActiveEvents
, COUNT(paId) AS Announcements
, COUNT(fbId) AS UserFeedback
FROM (
SELECT PlaceId, 1 AS peId, NULL AS paId, NULL AS fbId
FROM PlaceEvents
WHERE EndDateTimeUTC >= GETUTCDATE()
UNION ALL
SELECT PlaceId, NULL AS peId, 1 AS paId, NULL AS fbId
FROM PlaceAnnouncements
UNION ALL
SELECT PlaceId, NULL AS peId, NULL AS paId, 1 AS fbId
FROM PlaceFeedback
WHERE IsSystem = 0
) src
GROUP BY PlaceId
这个选择背后的想法,很容易进入视图,是从三个表中选择一个项目进行计数,然后将它们全部分组。
如果你有两个活动事件,一个公告和三个地方ID 123的反馈,那么三个内部选择将产生这个:
PlaceId peId paId fbId
------- ---- ---- ----
123 1 NULL NULL
123 1 NULL NULL
123 NULL 1 NULL
123 NULL NULL 1
123 NULL NULL 1
123 NULL NULL 1