Program Tip

SELECT DISTINCT가 지정된 경우 ORDER BY 항목이 선택 목록에 나타나야합니다.

programtip 2020. 11. 27. 21:09
반응형

SELECT DISTINCT가 지정된 경우 ORDER BY 항목이 선택 목록에 나타나야합니다.


선택 목록의 열을 순서별 목록에 추가했지만 여전히 오류가 발생합니다.

SELECT DISTINCT가 지정된 경우 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 1
 1 2
 2 1
 2 2
 2 3
 3 1

그런 다음 다음과 같이 쿼리하십시오.

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

행당 여러 될 수 있기 때문에 의미가 없습니다 col2. 주문시 어느 것을 사용해야합니까? 물론이 쿼리에서 결과가 그렇게되지 않을 것이라는 것을 알고 있지만 데이터베이스 서버는이를 미리 알 수 없습니다.

자, 당신의 경우는 조금 다릅니다. order by절에있는 select절의 모든 열을 포함 했으므로 언뜻보기에 모두 그룹화 된 것처럼 보입니다. 그러나 이러한 열 중 일부는 계산 된 필드에 포함되었습니다. distinct와 함께이를 수행하면 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. 열 별칭 사용 :

    RadioServiceCodeId, RadioService로 주문

  2. 열 위치 사용 :

    1,2로 정렬

DISTINCT 쿼리의 결과에 실제로 나타나는 열을 기준으로 만 정렬 할 수 있습니다. 기본 데이터는 정렬 할 수 없습니다.


연결을 정의 할 때 SQL 2008을 사용하는 DISTINCT Some Ex와 결합하여 정렬하려면 새 열에 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

Distinct and Group By generally do the same kind of thing, for different purposes... They both create a 'working" table in memory based on the columns being Grouped on, (or selected in the Select Distinct clause) - and then populate that working table as the query reads data, adding a new "row" only when the values indicate the need to do so...

The only difference is that in the Group By there are additional "columns" in the working table for any calculated aggregate fields, like Sum(), Count(), Avg(), etc. that need to updated for each original row read. Distinct doesn't have to do this... In the special case where you Group By only to get distinct values, (And there are no aggregate columns in output), then it is probably exactly the same query plan.... It would be interesting to review the query execution plan for the two options and see what it did...

Certainly Distinct is the way to go for readability if that is what you are doing (When your purpose is to eliminate duplicate rows, and you are not calculating any aggregate columns)


You could try a subquery:

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

반응형