我正在试图弄清楚如何在查询中找回真/假值。这是我正在尝试但它无法正常工作。
SELECT TOP 10
t1.Id as UserId,
CASE WHEN (t2.UserId = t1.Id AND t2.ItemId = 1) THEN CAST(1 as BIT) ELSE cast(0 as BIT) END as IsFavourite,
FROM Users t1
INNER JOIN UserFavorite t2 ON t1.Id = t2.UserId
GROUP BY t1.Id
我得到的错误是:
在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
我知道我需要在小组中分享一些内容才能使其工作,但我不明白。此外,查询已经简化,因为它连接了多个表。
只是为了澄清,收藏夹表基本上有Id,UserId,ItemId。因此,如果有用户和项目的组合,则表示它被收藏。
答案 0 :(得分:1)
SELECT TOP 10
t1.Id as UserId,
(CASE WHEN t2.ItemId = 1 THEN CAST(1 as BIT) ELSE
cast(0 as BIT) END) as IsFavourite,
FROM Users t1
INNER JOIN UserFavorite t2 ON t1.Id = t2.UserId
GROUP BY t1.Id,t2.ItemId
答案 1 :(得分:0)
SELECT TOP 10 *
FROM
(
SELECT
t1.Id as UserId
, CASE
WHEN (t2.UserId = t1.Id AND t2.ItemId = 1)
THEN CAST(1 as BIT)
ELSE cast(0 as BIT) END as IsFavourite
, ROW_NUMBER() OVER (PARTITION BY t1.Id ORDER BY (SELECT NULL)) rn
FROM Users t1
INNER JOIN UserFavorite t2 ON t1.Id = t2.UserId
) x
WHERE rn = 1