Using IN clause in sql server

2019-09-19 23:41发布

My query is like below.I want to select values if Type = 1 and subtype = 1,3 or 2.

select sum(case when Type = 1 and  SubType in (1, 3 or 2) then 1 else 0 end) as 'WorkStations'

Is this right way?

4条回答
▲ chillily
2楼-- · 2019-09-20 00:04

Try avoiding IN Predicates and instead use Joins because it Iterate unnecessarily despite of the fact that there is just one/two match. I will explain it with an example.

Suppose I have two list objects.

List 1      List 2
  1           12
  2            7
  3            8
  4           98
  5            9
  6           10
  7            6

Using IN, it will search for each List-1 item in List-2 that means iteration will happen 49 times !!!

查看更多
何必那么认真
3楼-- · 2019-09-20 00:05
SELECT COUNT(*) [Workstations] FROM [YourTable] t WHERE t.Type = 1 AND t.SubType IN (1, 2, 3) 
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-09-20 00:16

If you're simply counting records, your best bet is to use the COUNT function provided by SQL Server. Consider using the following:

SELECT COUNT(*) FROM [Table] WHERE TYPE = 1
                              AND (SUBTYPE = 1
                               OR  SUBTYPE = 2
                               OR  SUBTYPE = 3)

It is best to avoid using 'IN' as it can lead to unnecessary calls to the SQL engine.

查看更多
劳资没心,怎么记你
5楼-- · 2019-09-20 00:28

Since you're only trying to get a count of the workstations that meet the criteria as far as I can see:

SELECT COUNT(*) AS Workstations FROM MyWorkStationTable WHERE Type = 1 AND SubType IN (1, 2, 3)

Also, an IN clause is by nature already an OR. It is neither valid syntax nor necessary to state it.

查看更多
登录 后发表回答