Get a substring from a column and perform a groupBy and count

后端 未结 1 1157
一生所求
一生所求 2021-01-23 12:49

I have a table that stores data about a large number of files, such as their language, unique ID, file path etc. I want to be able to get the sub-string from the unique ID which

相关标签:
1条回答
  • 2021-01-23 13:12

    Sounds like you want a COUNT and a GROUP BY:

    SELECT 
      SUBSTRING(AssetID,1,2), 
      COUNT(*) Total
    FROM [table]
    GROUP BY SUBSTRING(AssetID,1,2)
    

    You did not specify what database but, if you are using SQL Server and LCID is in your SELECT statement, then you will need to include it in your GROUP BY clause.

    If the LCID value is unique for each row then you will get multiple records for each AssetID because it will try to group the unique values together. As a result, I removed the LCID.

    If it is not unique, then you can use:

    SELECT LCID, 
      SUBSTRING(AssetID,1,2), 
      COUNT(*) Total
    FROM [table]
    GROUP BY LCID, SUBSTRING(AssetID,1,2)
    

    Based on the edits that you made, you want a PIVOT which transforms the data from rows into columns. For a PIVOT you will use:

    select LCID, HA, HT, HP, FH, FX
    from
    (
      SELECT LCID, 
        SUBSTRING(AssetID,1,2) AssetID
      FROM [table]
    ) src
    pivot
    (
      count(AssetID)
      for AssetID in (HA, HT, HP, FH, FX) -- place more values here
    ) piv
    

    If the values are unknown that you want to transform into columns, then you will need to use dynamic SQL similar to this:

    DECLARE @cols AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)
    
    select @cols = STUFF((SELECT distinct ',' + QUOTENAME(SUBSTRING(AssetID,1,2)) 
                        from [table]
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    
    set @query = 'SELECT LCID, ' + @cols + ' from 
                 (
                    SELECT LCID, 
                      SUBSTRING(AssetID,1,2) AssetID
                    FROM [table]
                ) x
                pivot 
                (
                    count(AssetID)
                    for AssetID in (' + @cols + ')
                ) p '
    
    execute(@query)
    
    0 讨论(0)
提交回复
热议问题