我遇到的问题是我认为是一个分组条款。我试图用最早的InstallDate显示不同的CompanyID 这是我的代码:
SELECT
Pa.PARTY_ID
,MIN(SM.[INSTALLDATE]) INSTALLDATE
,SM.[STOPDATE]
FROM FORMDESC FD
INNER JOIN STATEINFO SI
ON FD.FORMDESCID = SI.FORMDESCID
INNER JOIN COMPANY C
ON FD.COMPANYID = C.COMPANYID
INNER JOIN PARTY Pa
ON C.COMPANYFULLNAME = Pa.FULL_NM
INNER JOIN STATEMARKET SM
ON SI.STATEINFOID = SM.STATEINFOID
WHERE ENTIREFORMNUMBER = 'ABC123'
GROUP BY PARTY_ID, INSTALLDATE, STOPDATE
我目前的输出是:
CompanyID | INSTALLDATE | STOPDATE
-------------------------------------------
60 | NULL | NULL
61 | 2015-09-26 00:00:00 | NULL
62 | NULL | NULL
62 | 2014-09-29 00:00:00 | NULL
62 | 2016-04-15 00:00:00 | NULL
我正在寻求的输出是:
CompanyID | INSTALLDATE | STOPDATE
----------------------------------------
60 | NULL | NULL
61 | 2015-09-26 00:00:00 | NULL
62 | 2014-09-29 00:00:00 | NULL
SM表上的左连接也不会帮助我。如果我从group by子句中提取任何值,我会收到错误。 这是一个我应该把它分成几个选择的情况吗?
虽然詹姆斯Z的答案确实有效;有人向我指出,我的小组包含INSTALLDATE导致了我的问题。
答案 0 :(得分:1)
你可能需要这样的东西:
select * from (
SELECT
Pa.PARTY_ID
,SM.[INSTALLDATE]
,SM.[STOPDATE]
,row_number() over (partition by Pa.PARTY_ID order by SM.[INSTALLDATE] desc) as RN
FROM FORMDESC FD
INNER JOIN STATEINFO SI
ON FD.FORMDESCID = SI.FORMDESCID
INNER JOIN COMPANY C
ON FD.COMPANYID = C.COMPANYID
INNER JOIN PARTY Pa
ON C.COMPANYFULLNAME = Pa.FULL_NM
INNER JOIN STATEMARKET SM
ON SI.STATEINFOID = SM.STATEINFOID
WHERE ENTIREFORMNUMBER = 'ABC123'
) X
where RN = 1
这将为每个party_id分别对行进行编号,然后显示其中最早的一行。这样,您可以从存在最小值的同一行获取其他数据。