我在SQL Server中工作,我希望获得表中每个字符串的出现次数。为此,我写了以下查询:
declare @tag table (TagName nvarchar(255), total int)
insert into @tag
select Tagname, count(TagName) Total
from tblTrend
where DigTagValue = 1
group by Tagname
select * from @tag
返回的输出是:
TagName Total
----------------------
P1Conv_Trip 1
P2Conv_Off 1
P2Conv_Trip 1
P3Conv_Off 1
Q1Conv_Off 1
Q2Conv_On 1
Q2Conv_Trip 1
Q3Conv_Off 2
Q3Conv_On 2
Q3Conv_Trip 1
W1Conv_Off 2
W1Conv_On 4
W1Conv_Trip 1
W2Conv_On 2
W2Conv_Trip 1
W3Conv_Off 1
W3Conv_On 1
W4Conv_Off 1
W4Conv_Trip 1
W5Conv_Off 1
W5Conv_On 2
W5Conv_Trip 1
但我想要的输出应该是这样的:
TagName ON OFF TRIP
------------------------------
P1 0 0 1
P2 0 1 1
P3 0 1 0
Q1 0 1 0
Q2 1 0 1
Q3 2 2 1
W1 4 2 1
W2 2 0 1
W3 1 1 0
W4 0 1 1
W5 2 1 1
如何实现此输出?
答案 0 :(得分:2)
无需使用临时表。试试这个查询
select
Tagname, [On] = count(case when suffix = 'On' then 1 end)
, [Off] = count(case when suffix = 'Off' then 1 end)
, [trip] = count(case when suffix = 'trip' then 1 end)
from (
select
Tagname = left(Tagname, 2)
, suffix = substring(Tagname, charindex('_', Tagname) + 1, 4)
from
tblTrend
where
DigTagValue=1
) t
group by Tagname
答案 1 :(得分:1)
试试这个(我只考虑你的部分数据,以显示逻辑:)):
declare @x table(TagName varchar(30), Total int)
insert into @x values
('P1Conv_Trip',1),
('P2Conv_Off',1),
('P2Conv_Trip',1),
('P3Conv_Off',1),
('Q1Conv_Off',1),
('Q2Conv_On',1),
('Q2Conv_Trip',1),
('Q3Conv_Off',2),
('Q3Conv_On',2),
('Q3Conv_Trip',1)
select [Tag],
MAX(case when [status] = 'On' then [total] else 0 end) [ON],
MAX(case when [status] = 'Off' then [total] else 0 end) [OFF],
MAX(case when [status] = 'Trip' then [total] else 0 end) [TRIP]
from (
select SUBSTRING(TagName, 1, 2) [Tag],
SUBSTRING(TagName, 8, LEN(tagname)) [Status],
Total
from @x
) a group by [Tag]
答案 2 :(得分:1)
你也可以使用如下PIVOT:
;WITH T AS
(
SELECT
LEFT(TagName,2) AS TagName,
SUBSTRING(TagName,CHARINDEX('_',TagName,0)+1,LEN(TagName)) AS ActionName,
Total
FROM @tblTest
)
SELECT
TagName,
SUM(ISNULL([On],0)) AS [ON],SUM(ISNULL([Off],0)) AS [Off],SUM(ISNULL([Trip],0)) AS Trip
FROM T
PIVOT (
MAX(Total) FOR ActionName IN ([ON],[Off],[Trip])
) pvt
GROUP BY TagName