i have a table 'DEMO' like below, I need some specified result in my select query
我有一个表'DEMO'如下,我需要在我的选择查询中的一些指定结果
PID Is_Viewed
1 False
1 False
1 False
1 False
2 True
2 False
Now i need to select only those record which if having even a single value 'True' then result will be 1 else 0 in select statment. i have tried much but not getting the desired result... my query is
现在我只需要选择那些记录,如果甚至只有一个值'True',那么结果将是选择参数中的其他0。我已经尝试了很多,但没有得到理想的结果...我的查询是
/// select statement
SELECT distinct PId,CASE WHEN EXISTS(Select Is_Viewed from DEMO where Is_viewed=1) then 1 else 0 end as Is_viewed FROM DEMO
i WANT result like
PId Is_Viewed
1 0
2 1
3 个解决方案
#1
3
Maybe something like this:
也许是这样的:
SELECT
PId,
MAX(CASE WHEN Is_Viewed='True' THEN 1 ELSE 0 END) AS Is_Viewed
FROM
DEMO
GROUP BY
PId
Edit
Considering the data that you have supplied.
考虑您提供的数据。
DECLARE @tbl TABLE(PID INT,Is_Viewed VARCHAR(10))
INSERT INTO @tbl
VALUES
(1,'False'),
(1,'False'),
(1,'False'),
(1,'False'),
(2,'True'),
(2,'False')
With this query
有了这个查询
SELECT
PId,
MAX(CASE WHEN Is_Viewed='True' THEN 1 ELSE 0 END) AS Is_Viewed
FROM
@tbl AS tbl
GROUP BY
PId
The output is this:
输出是这样的:
PId Is_Viewed
1 0
2 1
#2
0
I guess that Is_Viewed
is defined as a bit
type since SQL server doesn't have a BOOLEAN type. Then try this:
我猜Is_Viewed被定义为比特类型,因为SQL服务器没有BOOLEAN类型。然后尝试这个:
SELECT PID,
MAX(CAST(Is_Viewed as INT)) as Is_Viewed
FROM T
GROUP BY PID
#3
0
DECLARE @tbl TABLE(PID INT,Is_Viewed VARCHAR(10))
INSERT INTO @tbl
VALUES
(1,'False'),
(1,'False'),
(1,'False'),
(1,'False'),
(2,'True'),
(2,'False')
select distinct t.PID,
CASE WHEN t.Is_Viewed = 'TRUE'
THEN 1 ELSE 0 END As PType from @tbl t
INNER JOIN
(Select MIN(PID)As PID,Is_Viewed
FROM @tbl
GROUP BY Is_Viewed)AS KK
ON KK.PID = t.PID
AND KK.Is_Viewed = t.Is_Viewed
#1
3
Maybe something like this:
也许是这样的:
SELECT
PId,
MAX(CASE WHEN Is_Viewed='True' THEN 1 ELSE 0 END) AS Is_Viewed
FROM
DEMO
GROUP BY
PId
Edit
Considering the data that you have supplied.
考虑您提供的数据。
DECLARE @tbl TABLE(PID INT,Is_Viewed VARCHAR(10))
INSERT INTO @tbl
VALUES
(1,'False'),
(1,'False'),
(1,'False'),
(1,'False'),
(2,'True'),
(2,'False')
With this query
有了这个查询
SELECT
PId,
MAX(CASE WHEN Is_Viewed='True' THEN 1 ELSE 0 END) AS Is_Viewed
FROM
@tbl AS tbl
GROUP BY
PId
The output is this:
输出是这样的:
PId Is_Viewed
1 0
2 1
#2
0
I guess that Is_Viewed
is defined as a bit
type since SQL server doesn't have a BOOLEAN type. Then try this:
我猜Is_Viewed被定义为比特类型,因为SQL服务器没有BOOLEAN类型。然后尝试这个:
SELECT PID,
MAX(CAST(Is_Viewed as INT)) as Is_Viewed
FROM T
GROUP BY PID
#3
0
DECLARE @tbl TABLE(PID INT,Is_Viewed VARCHAR(10))
INSERT INTO @tbl
VALUES
(1,'False'),
(1,'False'),
(1,'False'),
(1,'False'),
(2,'True'),
(2,'False')
select distinct t.PID,
CASE WHEN t.Is_Viewed = 'TRUE'
THEN 1 ELSE 0 END As PType from @tbl t
INNER JOIN
(Select MIN(PID)As PID,Is_Viewed
FROM @tbl
GROUP BY Is_Viewed)AS KK
ON KK.PID = t.PID
AND KK.Is_Viewed = t.Is_Viewed