简体   繁体   English

计算SQL查询中前缀的匹配数

[英]Count the number of matches for a prefix in a SQL query

I have a table in an SQL server that looks like the one below and I want to count the number of unique occurrences where specific prefixes are used in the data column, like "21:00:00". 我在SQL Server中有一张表,看起来像下面的表,我想计算在数据列中使用特定前缀的唯一出现的次数,例如“ 21:00:00”。

Dataset: 资料集:

+-------------------------+
|          data           |
+-------------------------+
| 21:00:00:24:ff:5e:3a:bd |
| 50:01:43:80:18:6b:2a:4c |
| 21:00:00:1b:32:0f:a7:54 |
| 10:00:00:90:fa:a8:da:2a |
+-------------------------+

Desired query output: 所需的查询输出:

+----------+----------+----------+
| 21:00:00 | 50:01:43 | 10:00:00 |
+----------+----------+----------+
|        2 |        1 |        1 |
+----------+----------+----------+

I have been able to get the query to count a single prefix at a time by using this: 通过使用以下命令,我已经能够一次查询一次单个前缀的查询:

SELECT COUNT(DISTINCT wwpn) AS "21:00:00" FROM table WHERE wwpn LIKE '21:00:00%'

However, I want to count multiple prefixes as shown in the desired query output. 但是,我想要计算多个前缀,如所需查询输出中所示。

I've been waiting for someone to do a dynamic pivot (like Matt said in the comments) but no one has done it yet : (...I tried it myself and this is what I managed... 我一直在等待有人做一个动态的枢轴(如马特在评论中说的那样),但还没有人做过:(...我自己尝试过,这就是我所设法的...

Query : Query

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + LEFT(QUOTENAME(data), 9) + ']' 
        FROM DataTable
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')

set @query = N'SELECT ' + @cols + N' from 
         (
            select LEFT(data, 8) as data, COUNT(*) as count
            from DataTable
            GROUP BY LEFT(data, 8)
        ) x
        pivot 
        (
            max(count)
            for data in (' + @cols + N')
        ) p '

exec sp_executesql @query;

Results:

10:00:00 | 21:00:00 | 50:01:43
---------|----------|---------
    1    |    2     |    1
---------|----------|---------

If you know the prefixes in advance then you can do something simple like this; 如果您事先知道前缀,则可以执行以下简单操作:

Create test data; 创建测试数据;

CREATE TABLE #TestData (FieldName nvarchar(50))
INSERT INTO #TestData
VALUES
 ('21:00:00:24:ff:5e:3a:bd')
,('50:01:43:80:18:6b:2a:4c')
,('21:00:00:1b:32:0f:a7:54')
,('10:00:00:90:fa:a8:da:2a')

Query 询问

SELECT
SUM(CASE WHEN FieldName LIKE '21:00:00%' THEN 1 ELSE 0 END) [21:00:00]
,SUM(CASE WHEN FieldName LIKE '50:01:43%' THEN 1 ELSE 0 END) [50:01:43]
,SUM(CASE WHEN FieldName LIKE '10:00:00%' THEN 1 ELSE 0 END) [10:00:00]
FROM #TestData

Result 结果

21:00:00    50:01:43    10:00:00
2           1           1

Use this query: 使用此查询:

SELECT LEFT([Data], 8) as prefix, count(*) as cnt
    FROM tableName
    GROUP BY LEFT([Data], 8);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM