SQL Server Can you use a COUNT() with a WHERE clause within a multi column SELECT [closed]

ppcbkaq5  于 2023-05-05  发布在  其他
关注(0)|答案(1)|浏览(135)

Closed. This question is not reproducible or was caused by typos . It is not currently accepting answers.

This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.

Closed yesterday.
Improve this question

I'm trying to add the result of a filtered COUNT() to a multi column SELECT as such:

INSERT INTO dbo.AuditTable(
      PlaceId,
      Latitude,
      Longitude,
      IsOpen,
      EventCount
    )
      SELECT
        PlaceId,
        Latitude,
        Longitude,
        IsOpen,
        EvCount
      FROM (UPDATE P
              SET
                IsOpen = OpenTimeCalc.IsOpen

            OUTPUT
              INSERTED.PlaceId,
              INSERTED.Location,
              INSERTED.Latitude,
              INSERTED.Longitude,
              INSERTED.IsOpen,
              (SELECT COUNT(*)
               FROM E
               WHERE Event.Date >= LT.LocalDateTime
               AND E.PlaceId = P.PlaceId) AS EvCount

           FROM Place AS P
           JOIN Timezone AS TZ
             ON TZ.TimezoneId = P.TimezoneId
           JOIN Event AS E
             ON P.PlaceId = Event.PlaceId

           CROSS APPLY (
             SELECT
               GETUTCDATE() AT TIME ZONE 'UTC' AT TIME ZONE TZ.Name AS LocalDateTime
           ) AS LT
     )

I'm using a nested DML.

But it doesn't seem to work and I can't find an example like this one online.

Is it possible?

I tried to look for an answer online because I tried to add the SELECT keyword before the COUNT() , to create a CROSS APPLY and to call it afterwards but nothing seems to work.

ws51t4hk

ws51t4hk1#

Initially sub-query is executed inside curly braces. I think your sub-query is wrong. Count(*) is wrong. Because SQL Server does not know which columns get counts. This is my guess code. Maybe this is not work. But the structure should like this.

SELECT
    [PlaceId],
    [Latitude],
    [Longitude],
    [IsOpen],
    (
        SELECT COUNT(*)
        FROM [E]
        WHERE [Event].[Date] >= [LT].[LocalDateTime]
        AND [E].[PlaceId] = [LT].[PlaceId]
    ) AS [EvCount]
FROM [LT]

相关问题