开发者

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

开发者 https://www.devze.com 2023-02-06 18:01 出处:网络
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)

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 structu开发者_如何学运维re:-

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
0

精彩评论

暂无评论...
验证码 换一张
取 消