我想在语句中汇总null,这样它只会返回一个记录,它目前正在返回6条记录,每年一条记录。我希望id每年只返回一次结果。
sed -e '/pattern/N;y/\n/\t/'
答案 0 :(得分:0)
没有数据很难分辨,但我想你想从分组中删除SOURCE_CODE和CATEGORY(即只是按a.id分组),并在每个case语句周围添加MAX(...)。
作为旁边''是一个空字符串,而不是NULL。
编辑:为查询的黑客攻击版本创建了一些测试数据(即删除不相关的字段,并为了清晰起见缩短为3年)以显示我的意思:
create table #basic (
ID nvarchar(7),
CURRENT_COUNTY nvarchar(2)
)
insert into #basic values('1003986','37')
create table #activity (
ID nvarchar(7),
SOURCE_CODE nvarchar(4),
CATEGORY nvarchar(3)
);
insert into #activity (ID, SOURCE_CODE, CATEGORY) values('1003986', '2012','PC');
insert into #activity (ID, SOURCE_CODE, CATEGORY) values('1003986', '2014','PCG');
DECLARE @county nvarchar(2) = '37'
SELECT
A.ID,
MAX(CASE
when a.SOURCE_CODE='2012'and a.category='PC' then 'Presidents Club'
when a.SOURCE_CODE='2012'and a.category='PCG' then 'Presidents Club Gold'
when a.SOURCE_CODE='2012'and a.category='PCS' then 'Presidents Club Silver'
else ''
END) AS '2012',
MAX(CASE
when a.SOURCE_CODE='2013'and a.category='PC' then 'Presidents Club'
when a.SOURCE_CODE='2013'and a.category='PCB' then 'Presidents Club Broze'
when a.SOURCE_CODE='2013'and a.category='PCG' then 'Presidents Club Gold'
when a.SOURCE_CODE='2013'and a.category='PCS'
then 'Presidents Club Silver'
else ''
END) AS '2013',
MAX(CASE
when a.SOURCE_CODE='2014'and a.category='PC' then 'Presidents Club'
when a.SOURCE_CODE='2014'and a.category='PCB' then 'Presidents Club Broze'
when a.SOURCE_CODE='2014'and a.category='PCG' then 'Presidents Club Gold'
when a.SOURCE_CODE='2014'and a.category='PCS' then 'Presidents Club silver'
else ''
END) AS '2014'
FROM #basic AS b
INNER JOIN #Activity AS a ON b.ID = a.ID
WHERE
b.CURRENT_COUNTY = @county
AND A.ID = '1003986'
AND CATEGORY in ('PC','PCB','PCG','PCP','PCS')
GROUP BY a.id
返回
ID----- 2012----------- 2013--- 2014----------------
1003986 Presidents Club Presidents Club Gold
答案 1 :(得分:0)
从这个应该起作用的查询开始:
SELECT a.id, a.SOURCE_CODE, a.CATEGORY, COUNT(*)
FROM basic b INNER JOIN
Activity a
ON b.ID = a.ID
WHERE a.UF_3 In ('N', 'R') AND
a.UF_2 = 'v' AND
a.ACTION_CODES = 'A' AND
b.CURRENT_COUNTY = @county AND
PRODUCT_CODE = 'CHAPT/37'
A.ID = '1003986'
CATEGORY in ('PC', 'PCB', 'PCG', 'PCP', 'PCS')
GROUP BY a.id, a.SOURCE_CODE, a.CATEGORY
ORDER BY a.id, a.SOURCE_CODE;
这会将类别和源代码放在不同的行上。这可能足以满足您的目的。