1

假设我有这个代码:

DECLARE @IncludeDuplicateAddressIDs tinyint

-- Value of @IncludeDuplicateAddressIDs set here ! --

IF(@IncludeDuplicateAddressIDs = 1)
     SELECT AddressIds FROM RTS.ADDRESSES
ELSE
     SELECT DISTINCT(AddressIds) FROM RTS.ADDRESSES

我可以将这两个SELECT语句合二为一吗?也就是说,只使用一个SELECT,我要么显示所有 AddressID,要么只显示一个?

4

5 回答 5

2

你可以这样做:

SELECT AddressIds FROM RTS.ADDRESSES WHERE @IncludeDuplicateAddressIDs = 1
UNION ALL
SELECT DISTINCT(AddressIds) FROM RTS.ADDRESSES WHERE @IncludeDuplicateAddressIDs <> 1

由于WHERE子句是互斥的,只有一个UNION-ed 查询会返回一些行;另一个查询将不返回任何内容。

于 2013-04-18T11:00:50.527 回答
1

如果表包含唯一列,那么您可以使用此选项(假设唯一列的名称为Id):

DECLARE @IncludeDuplicateAddressIDs tinyint = 1
SELECT AddressIds
FROM RTS.ADDRESSES
GROUP BY CASE WHEN @IncludeDuplicateAddressIDs = 1 
              THEN Id ELSE AddressIds END, AddressIds  

SQLFiddle上的演示

于 2013-04-18T12:49:12.840 回答
0

您可以使用sp_executesql动态 sql 将查询形成为字符串(并根据需要设置任意数量的列),然后执行它:

DECLARE @IncludeDuplicateAddressIDs tinyint
DECLARE @Columns varchar(500);  

IF(@IncludeDuplicateAddressIDs = 1) SET @Columns='AddressIds'
ELSE SET @Columns='DISTINCT(AddressIds)'

EXECUTE sp_executesql N'SELECT ' + @Columns +  'AddressIds FROM RTS.ADDRESSES';
于 2013-04-18T11:03:49.193 回答
0

您可以包括重复地址的数量。

SELECT AddressIDs, count(*) as cnt
FROM RTS.ADDRESSES
GROUP BY AdressIDs
于 2013-04-18T10:57:51.843 回答
0

试试这个——

DECLARE @IncludeDuplicateAddressIDs TINYINT 
SELECT @IncludeDuplicateAddressIDs = 0

SELECT t.AddressIds
FROM (
    SELECT 
          AddressIds
        , cnt = ROW_NUMBER() OVER (PARTITION BY AddressIds ORDER BY AddressIds)
    FROM RTS.ADDRESSES
) t
WHERE @IncludeDuplicateAddressIDs = 1
    OR (@IncludeDuplicateAddressIDs != 1 AND cnt = 1)

在此查询中,未使用 UNION 或 DISTINCT 构造。因此,SQL 可以生成更高效的查询计划。

于 2013-04-18T11:09:11.587 回答