Sql server 消除嵌套选择中的多余行
我试图获得指定范围内的特定用户等级。当我在下面使用它时,它可以工作,没有额外的行:Sql server 消除嵌套选择中的多余行,sql-server,select,nested,duplicate-removal,Sql Server,Select,Nested,Duplicate Removal,我试图获得指定范围内的特定用户等级。当我在下面使用它时,它可以工作,没有额外的行: Select Distinct(Table2.AccountNumber), Jan11=Case When Datepart(yy,Org.Billdate)=2011 and Datepart(mm,Org.Billdate) = 01 then Table2.UserRating END From ( Select Distinct(Table1.AccountNumb
Select
Distinct(Table2.AccountNumber),
Jan11=Case
When Datepart(yy,Org.Billdate)=2011 and Datepart(mm,Org.Billdate) = 01 then Table2.UserRating
END
From (
Select Distinct(Table1.AccountNumber) as UseThisNumber, Table1.RegionID as UseThisRegionID
From AccountDetail Table1
Where Table1.RegionID in (
Select Distinct(Reg.RegionID)
From RegionOrganizationTable Reg where Datepart(yy,Reg.Billdate)=2011 and Datepart(mm,Reg.Billdate) = 01) and
Table1.UserRating in (‘Very Satisfied’, ‘Mostly Satisfied, ‘Satisfied’)
Group by Table1.AccountNumber, Table1.RegionID) GroupedValues,
AccountDetail Table2
RegionOrganizationTable Org
Where Table2.AccountNumber =GroupedValues.UseThisNumber
and Table2 UseThisRegionID=GroupedValues.UseThisRegionID
and Org.RegionID= GroupedValues.UseThisRegionID
Order by Table2.AccountNumber
但是,当我将嵌套组件中的Datepart条件更改为:
Datepart(yy,Reg.Billdate)>2010
(因为这确实是我要检查的日期范围),并删除:
Datepart(mm,Reg.Billdate)=01
从2011年1月开始的所有先前符合条件的AccountNumber都将重复,但返回空值。当我加上其他月份时,这是复合的(即,当……时,Feb11=情况)
以下是第一个场景中的输出:
账号…..Jan11123456…………非常满意
143457…………基本满意
163458…………满意
183459…………非常满意
203460…………非常满意
这里是第二个(为了便于识别,我用粗体显示重复项) 账号…..Jan11
123456…………非常满意
123456…………空
123499………..空
133499………..空
143457………..大部分满意
143457………..空
143499………..空
153499………..空
163458………..空
163458……满意
173458………..空
173499………..空
183459…………非常满意
183459…………空
183499………..空
193459…………空
203460………..空
203460…………非常满意
只是一个建议:如果您的意思是
年
,请说年
,如果您的意思是月
,请说月
。这些速记是懒惰的蠕虫罐头。尝试选择DATEPART(y,GETDATE())代码>来了解我的意思。如果您显示一些示例数据和所需的结果(可能使用),我们可能可以编写一个比尝试修复这里的内容更好的查询DISTINCT()
围绕单个列名以及所有这些嵌套的子查询和子选择,使我相信您需要的实际查询要简单得多。@AaronBertrand感谢您的反馈。我是一个新手,通过黑客破解我的方法,它显示:)无论如何,我编辑了OP以显示输出结果。