简体   繁体   English

SQL 使用不同的条件和多列分组

[英]SQL Group by using different conditions and multiple columns

I have an Addresses Table, with columns being: A,B,C,D......Address, Number, State, City, Zip **我有一个地址表,列是: A,B,C,D......地址,号码,State,城市,Zip **

I need to get a count of distinct addresses that can be grouped by 2 different conditions:我需要计算可以按 2 个不同条件分组的不同地址:

(Address, Number, State, City) OR (Address, Number, Zip) (地址、号码、State、城市)或(地址、号码、邮编)

The reason for the 2 conditions is that Zip can be null in some cases with City and State provided and vice versa.这 2 个条件的原因是 Zip 在某些情况下可以是 null 和 State 提供,反之亦然。 However, in cases where all 3 are present, the final table should just have 1 row for that address但是,在所有 3 个都存在的情况下,最终表应该只有 1 行用于该地址

select State, City, Address, Number
into T1
from Main Table
group by State, City, Address, Number

select Zip, Address, Number
into T2
from Main Table
group by Zip, Address, Number

select a.*, b.Zip into JoinT1T2 from T1 a inner join T2 b 
on a.Address=b.Address AND a.Number=b.Number 

select count(*) from JoinT1T2

But this is not giving me the desired result.但这并没有给我想要的结果。

You can create a new field called TypeOfDir, using the CASE instruction to get a value from 1 to 3 for the differents conditions that you have.您可以创建一个名为 TypeOfDir 的新字段,使用CASE指令为您拥有的不同条件获取一个从 1 到 3 的值。 Then you can group by that new field.然后您可以按该新字段进行分组。

What you need to do is define the condition as an extra column.您需要做的是将条件定义为额外的列。 You don't need to add this to the table (although it will help performance), you can do this on the fly if you want, by using CROSS APPLY .您不需要将其添加到表中(尽管它会提高性能),如果您愿意,可以使用CROSS APPLY即时执行此操作。

SELECT COUNT(*) FROM (
    SELECT DISTINCT HasZip, State, City, Zip, Address, Number
    FROM Table t
    CROSS APPLY (VALUES (CASE WHEN Zip IS NULL THEN 0 ELSE 1 END) ) v(HasZip)
) t

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

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