it-source

SELECT DISTING이 지정된 경우 ORDER BY 항목이 선택 목록에 표시되어야 합니다.

criticalcode 2023. 4. 21. 20:59
반응형

SELECT DISTING이 지정된 경우 ORDER BY 항목이 선택 목록에 표시되어야 합니다.

선택 목록의 열을 주문 기준 목록에 추가했지만 여전히 오류가 발생합니다.

SELECT DISTING을 지정한 경우 ORDER BY 항목이 선택 목록에 표시되어야 합니다.

저장된 proc는 다음과 같습니다.

CREATE PROCEDURE [dbo].[GetRadioServiceCodesINGroup] 
@RadioServiceGroup nvarchar(1000) = NULL
AS
BEGIN
SET NOCOUNT ON;

SELECT DISTINCT rsc.RadioServiceCodeId,
                rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
FROM sbi_l_radioservicecodes rsc
INNER JOIN sbi_l_radioservicecodegroups rscg 
ON rsc.radioservicecodeid = rscg.radioservicecodeid
WHERE rscg.radioservicegroupid IN 
(select val from dbo.fnParseArray(@RadioServiceGroup,','))
OR @RadioServiceGroup IS NULL  
ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService

END

이것을 시험해 보세요.

ORDER BY 1, 2

또는

ORDER BY rsc.RadioServiceCodeId, rsc.RadioServiceCode + ' - ' + rsc.RadioService

같은 것은 아니지만 어떤 의미에서는DISTINCT를 암시하다GROUP BY왜냐하면DISTINCT를 사용하여 다시 쓸 수 있습니다.GROUP BY대신.이 점을 염두에 두고 집약 그룹에 없는 것을 주문하는 것은 의미가 없습니다.

예를 들어 다음과 같은 테이블이 있는 경우:

col1 col2----  ----1     11     22     12     22     33     1

그리고 다음과 같이 쿼리를 시도합니다.

SELECT DISTINCT col1 FROM [table] WHERE col2 > 2 ORDER BY col1, col2

그건 말이 안 돼요 결국엔 여러 명이 있을 수 있기 때문이죠col2값을 지정합니다.주문에는 어떤 것을 사용해야 하나요?물론 이 쿼리에서는 결과가 그렇지 않다는 것을 알 수 있지만 데이터베이스 서버는 이를 미리 알 수 없습니다.

자, 당신의 경우는 조금 다릅니다.의 모든 열을 포함했습니다.order by의 조항select그래서 언뜻 보면 모두 그룹화되어 있는 것처럼 보일 것이다.그러나 이러한 열 중 일부는 계산된 필드에 포함되었다.그것을 구별하는 것과 조합하면,distinct디렉티브는 계산의 최종 결과에만 적용할 수 있으며 계산의 소스에 대해서는 더 이상 아무것도 알 수 없습니다.

즉, 서버는 더 이상 이러한 열에 의존할 수 없다는 것을 알 수 없습니다.사용된 것은 알고 있지만 계산 연산이 위의 첫 번째 간단한 예시와 유사한 효과를 가져올지는 알 수 없습니다.

이제 다른 작업을 수행하여 컬럼을 주문에 사용할 수 있음을 서버에 알려야 합니다.여기에는 몇 가지 방법이 있지만, 이 접근방식은 정상적으로 동작합니다.

SELECT rsc.RadioServiceCodeId,
            rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
FROM sbi_l_radioservicecodes rsc
INNER JOIN sbi_l_radioservicecodegroups rscg 
    ON rsc.radioservicecodeid = rscg.radioservicecodeid
WHERE rscg.radioservicegroupid IN 
    (SELECT val FROM dbo.fnParseArray(@RadioServiceGroup,','))
    OR @RadioServiceGroup IS NULL  
GROUP BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService

다음 중 하나를 시도해 보십시오.

  1. 열 별칭 사용:

    Radio Service Code Id, Radio Service

  2. 열 위치 사용:

    주문 기준 1,2

DISTINT 쿼리 결과에 실제로 나타나는 열로만 정렬할 수 있습니다. 기본 데이터는 주문에 사용할 수 없습니다.

Distributed와 Group By는 보통 같은 종류의 일을 하는데, 다른 목적을 위해서...둘 다 그룹화되어 있는 열(또는 [Select Distinction]절에서 선택됨)을 기반으로 메모리에 '작업' 테이블을 만듭니다.그리고 쿼리가 데이터를 읽을 때 해당 작업 테이블을 채웁니다.이러한 값이 필요한 경우에만 새로운 '행'을 추가합니다.

유일한 차이점은 Group By의 작업 테이블에는 원래 행을 읽을 때마다 업데이트해야 하는 Sum(), Count(), Avg() 등의 계산된 집계 필드에 대한 추가 "컬럼"이 있다는 것입니다.Different가 꼭 이럴 필요는 없어그룹화 기준만 사용하여 고유한 값을 얻는 특별한 경우(출력에는 집계 열이 없음)에는 동일한 쿼리 계획일 수 있습니다.두 가지 옵션에 대한 쿼리 실행 계획을 검토하여 어떤 결과를 얻었는지 보는 것이 흥미롭습니다.

확실히 구별이 가독성을 실현하기 위한 수단입니다(중복 행을 배제하고 집계 열을 계산하지 않는 경우).

연결을 정의할 때 새 컬럼에 대해 DISTINCT Some Ex with sql 2008을 주문하려면 ALIAS를 사용해야 합니다.

--this works 

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName 
    from SalesLT.Customer c 
    order by FullName

--this works too

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) 
    from SalesLT.Customer c 
    order by 1

-- this doesn't 

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName 
    from SalesLT.Customer c 
    order by c.FirstName, c.LastName

-- the problem the DISTINCT needs an order on the new concatenated column, here I order on the singular column
-- this works

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) 
        as FullName, CustomerID 
        from SalesLT.Customer c 

order by 1, CustomerID

-- this doesn't

    SELECT DISTINCT (c.FirstName + ' ' + c.LastName) as FullName 
     from SalesLT.Customer c 
      order by 1, CustomerID

서브쿼리를 시도해 볼 수 있습니다.

SELECT DISTINCT TEST.* FROM (
    SELECT rsc.RadioServiceCodeId,
        rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
    FROM sbi_l_radioservicecodes rsc
       INNER JOIN sbi_l_radioservicecodegroups rscg ON  rsc.radioservicecodeid = rscg.radioservicecodeid
    WHERE rscg.radioservicegroupid IN 
       (select val from dbo.fnParseArray(@RadioServiceGroup,','))
        OR @RadioServiceGroup IS NULL  
    ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
) as TEST

언급URL : https://stackoverflow.com/questions/265628/order-by-items-must-appear-in-the-select-list-if-select-distinct-is-specified

반응형