Search code examples
sqlt-sqldd

T-SQL Problem


I have following table (SQL Server) Table name is LandParcels

Blockid   ParcelNo  Stateorprivate
========================
11001901   30       Deemana
11001901   35       Deemana
11001901   41       State
11001901   45       State
11001901   110      Private
11001901   111      Private

11001902   1        Deemana
11001902   11       State
11001902   16       Private

11002001   15       Deemana
11002001   16       State
11003001   20       Private
11002003   2        Deemana
11002003   3        State
11003003   4        Private

Blockid (Numeric) = first 6 digits used for Cadastral Map No and last 2 digits for the Block No

eg: 110019 is Cadastal map no and 01 is Block No.

I used the following query

select substring(ltrim(str(blockid)),1,6) as blockid,stateorprivate, count(*) as noofLP from LandParcels group by blockid, stateorprivate order by blockid asc

Result is

Blockid  Stateorprivate  noofLP
========================
110019   Deemana         2
110019   State           2
110019   Private         2
110019   Deemana         1
110019   State           1
110019   Private         1
110020   Deemana         1
110020   State           1
110020   Private         1
110020   Deemana         1
110020   State           1
110020   Private         1

I want to get the following result for a report

blockid  noofBlocks   Deemana   State  Private  Amt_of_Deemana_State_Private
110019    2            3          3       3          9  
110020    2            2          2       2          6

How to query this. Pl help me.


Solution

  • You could do something like this:

    SELECT 
        SUBSTRING(LTRIM(STR(Blockid)), 1, 6) AS blockid,
        COUNT(DISTINCT SUBSTRING(LTRIM(STR(Blockid)), 7, 2)) AS noofBlocks,
        SUM(CASE Stateorprivate WHEN 'Deemana' THEN 1 ELSE 0 END) AS Deemana,
        SUM(CASE Stateorprivate WHEN 'State' THEN 1 ELSE 0 END) AS [State],
        SUM(CASE Stateorprivate WHEN 'Private' THEN 1 ELSE 0 END) AS [Private],
        SUM(CASE Stateorprivate
            WHEN 'Deemana' THEN 1
            WHEN 'State' THEN 1
            WHEN 'Private' THEN 1
            ELSE 0
        END) AS Amt_of_Deemana_State_Private
    FROM LandParcels
    GROUP BY SUBSTRING(LTRIM(STR(Blockid)), 1, 6)
    

    However, if the database schema is under your control, you should consider normalization.