我已经加入了两个表,我想使用GROUP BY
,但出现错误。
我尝试替换所有列而不是*,但无法正常工作。
SELECT t.*
FROM
(select O.[CUSTADDRESSID]
,O.[ACCOUNTNO]
,O.[ADDRESSTYPE]
,O.[ADDRESSLINE1]
,O.[ISCOMMUNICATION]
,C.[CUSTOMERID]
,C.[ACCOUNTNO]
,C.[ACCOUNTGROUPID]
,C.[PREPAIDACCOUNTSTATUSID]
,C.[PREPAIDACCOUNTSTATUSDATE]
from [ISSUER].[HISTORY].[TP_CUSTOMER_PREPAIDACCOUNTS] c
full join [ISSUER].[PLAY].[TP_CUSTOMER_ADDRESSES] o
on c.ACCOUNTNO = o.ACCOUNTNO) as t
group by ACCOUNTNO
我想从加入结果中删除重复的ACCOUNTNO
。
答案 0 :(得分:3)
使用t。*时,意味着您选择了所有列,但是仅按组使用了一个列,这就是为什么会出现此错误的原因,现在,如果您仅在选择中使用accountno,并使用过滤器来过滤重复的账户,则不会,那么您可以使用count
聚合函数以及下面的查询
SELECT [ACCOUNTNO]
FROM
(select O.[CUSTADDRESSID]
,O.[ACCOUNTNO]
,O.[ADDRESSTYPE]
,O.[ADDRESSLINE1]
,O.[ISCOMMUNICATION]
,C.[CUSTOMERID]
,C.[ACCOUNTNO] as C_ACCOUNTNO
,C.[ACCOUNTGROUPID]
,C.[PREPAIDACCOUNTSTATUSID]
,C.[PREPAIDACCOUNTSTATUSDATE]
from [ISSUER].[HISTORY].[TP_CUSTOMER_PREPAIDACCOUNTS] c
full join [ISSUER].[PLAY].[TP_CUSTOMER_ADDRESSES] o
on c.ACCOUNTNO = o.ACCOUNTNO
) as t
group by ACCOUNTNO
having count([ACCOUNTNO])>1
但是,如果您要查询,则必须使用distinct
SELECT distinct t.*
FROM
(select O.[CUSTADDRESSID]
,O.[ACCOUNTNO]
,O.[ADDRESSTYPE]
,O.[ADDRESSLINE1]
,O.[ISCOMMUNICATION]
,C.[CUSTOMERID]
,C.[ACCOUNTNO] as C_ACCOUNTNO
,C.[ACCOUNTGROUPID]
,C.[PREPAIDACCOUNTSTATUSID]
,C.[PREPAIDACCOUNTSTATUSDATE]
from [ISSUER].[HISTORY].[TP_CUSTOMER_PREPAIDACCOUNTS] c
full join [ISSUER].[PLAY].[TP_CUSTOMER_ADDRESSES] o
on c.ACCOUNTNO = o.ACCOUNTNO) as t
您可以了解有关group by
答案 1 :(得分:3)
您在内部查询中两次指定了相同的ACCOUNTNO
SELECT t.*
FROM
(
select O.[CUSTADDRESSID]
,O.[ACCOUNTNO] -- 1st occurance
,O.[ADDRESSTYPE]
,O.[ADDRESSLINE1]
,O.[ISCOMMUNICATION]
,C.[CUSTOMERID]
,C.[ACCOUNTNO] -- second occurance
,C.[ACCOUNTGROUPID]
,C.[PREPAIDACCOUNTSTATUSID]
,C.[PREPAIDACCOUNTSTATUSDATE]
from [ISSUER].[HISTORY].[TP_CUSTOMER_PREPAIDACCOUNTS] c
full join [ISSUER].[PLAY].[TP_CUSTOMER_ADDRESSES] o
on c.ACCOUNTNO = o.ACCOUNTNO) as t
--group by ACCOUNTNO
您可以使用ACCOUNTNO
示例之一的别名
,O.[ACCOUNTNO] AS ACCNO1
,C.[ACCOUNTNO] AS ACCNO2
或者或者
因为您正在对ACCOUNTNO做FULL OUTER JOIN
您应该使用COALESCE()
从TP_CUSTOMER_PREPAIDACCOUNTS
或TP_CUSTOMER_ADDRESSES
返回
将内部查询更改为
select O.[CUSTADDRESSID]
,COALESCE(O.[ACCOUNTNO], C.[ACCOUNTNO]) AS ACCOUNTNO
,O.[ADDRESSTYPE]
答案 2 :(得分:2)
您可以尝试以下查询:它将为您提供重复的帐户编号
SELECT [ACCOUNTNO],count([ACCOUNTNO])
FROM
(select O.[CUSTADDRESSID]
,O.[ACCOUNTNO]
,O.[ADDRESSTYPE]
,O.[ADDRESSLINE1]
,O.[ISCOMMUNICATION]
,C.[CUSTOMERID]
,C.[ACCOUNTNO] as accountno_c
,C.[ACCOUNTGROUPID]
,C.[PREPAIDACCOUNTSTATUSID]
,C.[PREPAIDACCOUNTSTATUSDATE]
from [ISSUER].[HISTORY].[TP_CUSTOMER_PREPAIDACCOUNTS] c
full join [ISSUER].[PLAY].[TP_CUSTOMER_ADDRESSES] o
on c.ACCOUNTNO = o.ACCOUNTNO) as t
group by ACCOUNTNO
having count([ACCOUNTNO])>1