简体   繁体   中英

Count entries across a SQL table

I currently have a table which is within a system which I am unable to change. So not the ideal format, I know, but I need to count across 6 columns to show if there is something entered and then put the sum in a final column. The entries are text and so I just need to know the total across the 6 columns.

[data1]
[data2]
[data3]
[data4]
[data5]
[data6]
--To be created [totalcount] 

If I understand correctly:

select t.*,
       ( (case when col1 is not null then 1 else 0 end) +
         (case when col2 is not null then 1 else 0 end) +
         (case when col3 is not null then 1 else 0 end) +
         (case when col4 is not null then 1 else 0 end) +
         (case when col5 is not null then 1 else 0 end) +
         (case when col6 is not null then 1 else 0 end)
       ) as num_notnull
from t;

First thing to consider is if an empty string ( '' ) is considered empty or not. Then you can do the following for the entire table:

SELECT
    COUNT(CASE WHEN T.Col1 IS NULL OR T.Col1 = '' THEN 1 END) Col1Blanks,
    COUNT(CASE WHEN T.Col2 IS NULL OR T.Col2 = '' THEN 1 END) Col2Blanks,
    COUNT(CASE WHEN T.Col3 IS NULL OR T.Col3 = '' THEN 1 END) Col3Blanks,
    COUNT(CASE WHEN T.Col4 IS NULL OR T.Col4 = '' THEN 1 END) Col4Blanks,
    COUNT(CASE WHEN T.Col5 IS NULL OR T.Col5 = '' THEN 1 END) Col5Blanks,
    COUNT(CASE WHEN T.Col6 IS NULL OR T.Col6 = '' THEN 1 END) Col6Blanks
FROM
    YourTable T

If you need the total of all of them ( ISNULL is a SQL Server function, every DMBS has one equivalent):

SELECT
    X.Col1Blanks,
    X.Col2Blanks,
    X.Col3Blanks,
    X.Col4Blanks,
    X.Col5Blanks,
    X.Col6Blanks,
    ISNULL(X.Col1Blanks, 0) +
        ISNULL(X.Col2Blanks, 0) +
        ISNULL(X.Col3Blanks, 0) +
        ISNULL(X.Col4Blanks, 0) +
        ISNULL(X.Col5Blanks, 0) +
        ISNULL(X.Col6Blanks, 0) TotalBlanks
FROM
    (
    SELECT
        COUNT(CASE WHEN T.Col1 IS NULL OR T.Col1 = '' THEN 1 END) AS Col1Blanks,
        COUNT(CASE WHEN T.Col2 IS NULL OR T.Col2 = '' THEN 1 END) AS Col2Blanks,
        COUNT(CASE WHEN T.Col3 IS NULL OR T.Col3 = '' THEN 1 END) AS Col3Blanks,
        COUNT(CASE WHEN T.Col4 IS NULL OR T.Col4 = '' THEN 1 END) AS Col4Blanks,
        COUNT(CASE WHEN T.Col5 IS NULL OR T.Col5 = '' THEN 1 END) AS Col5Blanks,
        COUNT(CASE WHEN T.Col6 IS NULL OR T.Col6 = '' THEN 1 END) AS Col6Blanks
    FROM
        YourTable T
    ) X

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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