简体   繁体   English

SQL Server:在变量多列上使用 DISTINCT 进行 SELECT

[英]SQL Server : SELECT with DISTINCT on variable multiple columns

I need to count the number of distinct items from this table but the distinct is over many columns stocked in a variable.我需要计算该表中不同项目的数量,但不同的是存储在变量中的许多列。 This is 2 req.这是 2 个请求。

Req 1:要求 1:

SELECT COUNT(DISTINCT (CHECKSUM(code_paiement,id_emetteur,id_liaison)))
FROM [DB1].[dbo].[Vo_Fait]

Req 2:要求 2:

declare @var nvarchar(4000) = 'code_paiement, id_emetteur, id_liaison'

SELECT COUNT(DISTINCT (CHECKSUM(@var)))
FROM [DB1].[dbo].[Vo_Fait]

But the result of this 2 req is different !但是这 2 个请求的结果是不同的!

  • Result req 1 : 45205结果请求 1:45205
  • Result req 2 : 1结果要求 2 : 1

In "req2" you're taking the checksum of the string 'code_paiement,id_emetteur,id_liaison', which will always be the same, and counting the distinct values of it, which will always be 1.在“req2”中,您正在获取字符串“code_paiement,id_emetteur,id_liaison”的校验和,它总是相同的,并计算它的不同值,它总是为 1。

Think of it this way: your code reduces to:这样想:您的代码简化为:

SELECT COUNT(DISTINCT (CHECKSUM('code_paiement,id_emetteur,id_liaison')))
FROM [DB1].[dbo].[Vo_Fait]

...which is the same as: ...与以下内容相同:

SELECT COUNT(DISTINCT (-1998057055))
FROM [DB1].[dbo].[Vo_Fait]

So you're counting the number of distinct occurrences of the number -1998057055 for every row in the table;因此,您正在计算表中每一行的数字 -1998057055 的不同出现次数; as the value is the same for every row, there is only one distinct occurrence.由于每一行的值都相同,因此只有一个不同的事件。

If you really need to build your SQL code dynamically (generally you should avoid this if possible by changing your design), then you should use something like exec or sp_executesql .如果你真的需要动态构建你的 SQL 代码(通常你应该通过改变你的设计来避免这种情况),那么你应该使用类似execsp_executesql东西。 A trivial example:一个简单的例子:

DECLARE @var NVARCHAR(4000) = 'code_paiement,id_emetteur,id_liaison';
DECLARE @sql NVARCHAR(4000)='SELECT COUNT(DISTINCT(CHECKSUM(' + @var + '))) FROM [DB1].[dbo].[Vo_Fait]';
EXEC (@sql);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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