我有一张桌子,如下:
Type_id name Comments
-------------------
61 a aa
62 a Test2
62 b bb
63 c cc
63 b bb
63 c bb
64 c cc
现在,我要选择如下结果集:
Type_id name Comments
-------------------
61 a aa
62 a Test2
b bb
63 c cc
b bb
c bb
64 c cc
如果有多个值,重复的Type_id应该显示一个空字符串。我尝试使用CASE语句,但运气不佳。
这是我尝试过的查询:
select
case when Type_id = 61 then 'Cell1'
when Type_id = 62 then 'Cell2'
when Type_id = 63 then 'Cell3'
else ''
end as Type_id,
name,
Comments
FROM
TBL
where
CATEGORY_ID = 120
order by Type_id
谁能帮助我。预先感谢。
答案 0 :(得分:2)
我结合了LAG和CASE来解决:
# version 2
def schedule_single_scoring(
submission: Submission,
scoring_specification: ScoringSpecification) -> SubmissionScore:
"""multiline docstrings are present"""
# version 3
def schedule_single_scoring(submission: Submission, scoring_specification:
ScoringSpecification) -> SubmissionScore:
答案 1 :(得分:1)
这是我的版本
--temp data
if object_id('tempdb..#x') is not null drop table #x
CREATE TABLE #x(type_id INT, name VARCHAR(1), comments VARCHAR(20))
INSERT INTO #x(type_id, name, comments) VALUES
( 61, 'a', 'aa'),
( 62, 'a', 'Test2'),
( 62, 'b', 'bb'),
( 63, 'c', 'cc'),
( 63, 'b', 'bb'),
(63, 'c', 'bb'),
(64, 'c', 'cc')
--query
SELECT CASE WHEN type_id=LAG(type_id,1,0) OVER(ORDER BY type_id) THEN NULL ELSE type_id END AS 'type_id',
name, comments
FROM #x
输出
type_id name comments
61 a aa
62 a Test2
NULL b bb
63 c cc
NULL b bb
NULL c bb
64 c cc
如果您没有请求者声明的LAG,则
if object_id('tempdb..#x') is not null drop table #x
CREATE TABLE #x(type_id INT, name VARCHAR(1), comments VARCHAR(20))
INSERT INTO #x(type_id, name, comments) VALUES
( 61, 'a', 'aa'),
( 62, 'a', 'Test2'),
( 62, 'b', 'bb'),
( 63, 'c', 'cc'),
( 63, 'b', 'bb'),
(63, 'c', 'bb'),
(64, 'c', 'cc')
if object_id('tempdb..#a') is not null drop table #a
SELECT x.*,
ROW_NUMBER() OVER(PARTITION BY x.type_id ORDER BY x.type_id) AS 'id_count'
INTO #a
FROM #x AS x
SELECT CASE WHEN a.id_count>1 THEN NULL ELSE a.type_id END AS 'type_id',
a.name, a.comments
FROM #a AS a
答案 2 :(得分:0)
select
case when row_number() -- only return 1st value
over (partition by Type_id
order by name) = 1
then cast(Type_id as varchar(10))
else ''
end as Type_id,
name,
Comments
FROM
TBL
where
CATEGORY_ID = 120
order by Type_id, name -- same order by used in ROW_NUMBER