0

I have a table with 2 columns plateno and alerts.

table Data

plateno    alerts
  A         1
  B         2
  C         2
  A         3
  B         2
  A         4
  A         1

Now I want to get the result like this:

alerts->   1  2  3  4
---------------------------
A          2  0  1  1
B          0  2  0  0
C          0  1  0  0

I mean 'A' has two alerts of type '1',1 alert of type '3' and '4'...and so on..

Here is my query I am trying with

Select count(alert) 
from mytable 
group by plateno
4

4 回答 4

2

尝试这个 :-

Select plateno,[1],[2],[3],[4]
from 
(
 Select plateno,alerts from Sample
)p
pivot 
(
 count(alerts)
 for alerts in ([1],[2],[3],[4])
)pvt

在这里演示

于 2013-05-06T04:31:54.110 回答
2

如果您有未知数量的列值,Alert则更优选动态 sql ,

DECLARE @colList AS NVARCHAR(MAX), @sqlStatement AS NVARCHAR(MAX)

SELECT @colList = STUFF((SELECT DISTINCT ',' + QUOTENAME(alerts) 
                    FROM data
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') ,1,1,'')


SET @sqlStatement = 'SELECT plateno,' + @colList + ' 
             FROM 
             (
                SELECT plateno, alerts 
                FROM data
             ) dta
             pivot 
             (
                COUNT(alerts)
                FOR alerts IN (' + @colList + ')
             ) pvt '

EXECUTE(@sqlStatement)

输出

╔═════════╦═══╦═══╦═══╦═══╗
║ PLATENO ║ 1 ║ 2 ║ 3 ║ 4 ║
╠═════════╬═══╬═══╬═══╬═══╣
║ A       ║ 2 ║ 0 ║ 1 ║ 1 ║
║ B       ║ 0 ║ 2 ║ 0 ║ 0 ║
║ C       ║ 0 ║ 1 ║ 0 ║ 0 ║
╚═════════╩═══╩═══╩═══╩═══╝
于 2013-05-06T04:36:09.753 回答
1

尝试这个:

SELECT plateno
,SUM(CASE alerts WHEN 1 THEN 1 ELSE 0 END) AS [1]
,SUM(CASE alerts WHEN 2 THEN 1 ELSE 0 END) AS [2]
,SUM(CASE alerts WHEN 3 THEN 1 ELSE 0 END) AS [3]
,SUM(CASE alerts WHEN 4 THEN 1 ELSE 0 END) AS [4]
FROM Table1
GROUP BY plateno

输出:

╔═════════╦═══╦═══╦═══╦═══╗
║ PLATENO ║ 1 ║ 2 ║ 3 ║ 4 ║
╠═════════╬═══╬═══╬═══╬═══╣
║ A       ║ 2 ║ 0 ║ 1 ║ 1 ║
║ B       ║ 0 ║ 2 ║ 0 ║ 0 ║
║ C       ║ 0 ║ 1 ║ 0 ║ 0 ║
╚═════════╩═══╩═══╩═══╩═══╝

看到这个 SQLFiddle

于 2013-05-06T04:31:34.530 回答
0
Select plateno,sum([1]) as [1],sum([2]) as [2],sum([3]) as [3],sum([4]) as [4]
from 
(
 Select plateno,
  case when alert=1 then 1 else 0 end as [1],
  case when alert=2 then 1 else 0 end as [2],
  case when alert=3 then 1 else 0 end as [3],
  case when alert=4 then 1 else 0 end as [4]
 from planet

 )z
group by plateno

SQL小提琴 在这里

于 2013-05-06T04:52:50.550 回答