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:-
- First record of column_01
- total count of column_01 (based on where condition)
- total count of column_02 (based on where condition)
- 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
精彩评论