I've been researching most of the morning on how to do a computed case statement and apply a where clause to the result.
I'm attempting a SEDE query that eliminates as many lines from the select with where, then apply a computation on the remaining. The computation is expensive, as it is several like matches with wildcards.
Simple example, let me call this column Pcount:
CASE WHEN Posts.Title LIKE '%?' THEN 1 ELSE 0 END
+
CASE WHEN Posts.Title LIKE 'H%' THEN 1 ELSE 0 END
For "How do I SQL?", PCount should = 2 (both matched).
For "Hello my name is Alice.", PCount should = 1 (only "H%" matched).
For "Am I wrong?", PCount should = 1 (only "%?" matched).
For anything else, PCount = 0.
My first attempt used WITH:
WITH MyPosts (Id, Score, OwnerUserId, LastActivityDate, Tags, PCount)
AS
(
Select
Posts.Id,
Posts.Score,
Posts.OwnerUserId,
Posts.LastActivityDate,
Posts.Tags,
(
CASE WHEN Posts.Title LIKE '%?' THEN 1 ELSE 0 END
+
CASE WHEN Posts.Title LIKE 'H%' THEN 1 ELSE 0 END
) as PCount
FROM Posts
WHERE
Posts.Score >= ##Score##
AND Posts.ClosedDate IS NULL
)
SELECT DISTINCT
MyPosts.Id AS [Post Link],
MyPosts.PCount,
MyPosts.Score AS [Post Score],
MyPosts.OwnerUserId AS [User Link],
MyPosts.LastActivityDate AS [Last Activity],
MyPosts.Tags
FROM Posts
WHERE
PCount > 1;
Line 34: Invalid column name 'PCount'.
The multi-part identifier "MyPosts.Id" could not be bound.
The multi-part identifier "MyPosts.PCount" could not be bound.
The multi-part identifier "MyPosts.Score" could not be bound.
The multi-part identifier "MyPosts.OwnerUserId" could not be bound.
The multi-part identifier "MyPosts.LastActivityDate" could not be bound.
The multi-part identifier "MyPosts.Tags" could not be bound.
But I've tried many ways, including without using WITH:
SELECT Pcount FROM Posts WHERE
(
CASE WHEN Posts.Title LIKE '%?' THEN 1 ELSE 0 END
+
CASE WHEN Posts.Title LIKE 'H%' THEN 1 ELSE 0 END
) AS Pcount
SELECT Pcount FROM Posts WHERE
(SELECT (
CASE WHEN Posts.Title LIKE '%?' THEN 1 ELSE 0 END
+
CASE WHEN Posts.Title LIKE 'H%' THEN 1 ELSE 0 END
)) as Pcount > 1
SELECT Pcount FROM Posts WHERE
(SELECT (
CASE WHEN Posts.Title LIKE '%?' THEN 1 ELSE 0 END
+
CASE WHEN Posts.Title LIKE 'H%' THEN 1 ELSE 0 END
) as Pcount) > 1;
I've read this as well as googled about adding case, but 99% of those links are not about adding. They tend to be "case blah=1 then yep1" string results.
Anyone have an example for me?
WITH
- you name your CTEMyPosts
but then usePosts
instead in your followingFROM
clause.