简体   繁体   中英

How to improve this transact-sql script for sql server 2005?

I have this script:-

SELECT TOP 1
    column_01, 
    COUNT(column_01) OVER(),
    (SELECT TOP 1 COUNT(column_02) FROM table_01 WHERE status = 1 and Column_02 = 1)
FROM 
    table_01
WHERE 
    status = 1
ORDER BY column_02 desc, datetimestamp asc

table_01 structure:-

column_01 int (primary key)
column_02 bit 
datetimestamp datetime

What I am trying to achieve:-

  1. First record of column_01
  2. total count of column_01 (based on where condition)
  3. total count of column_02 (based on where condition)
  4. Order by datetimestamp but if column_02 is true then that record should come at the top. Thats why I am using order by clause.

This query is doing what i want but I have a sense that there is a lot of scope to improve the query. So how can I improve this query in terms of performance and best practices? Thanks

You can avoid the inline query using SUM as given below:

SELECT TOP 1
        column_01, 
        COUNT(column_01) OVER(),
    SUM(CASE WHEN column_02=1 THEN 1 ELSE 0 END) OVER()
    FROM 
        table_01
    WHERE 
        status = 1
    ORDER BY column_02 desc, datetimestamp asc

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