简体   繁体   中英

How to retrieve data with group by aggregate function in SQL Server 2012

I am new to SQL Server 2012. This is my table DDL & DML script.

CREATE TABLE [tbl_item_i18n]
(
    [item_id] [int] NOT NULL,
    [lang_id] [int] NOT NULL,
    [item_text] [nvarchar](max) NULL
);

INSERT INTO [tbl_item_i18n] ([item_id],[lang_id],[item_text])
VALUES (1, 1, 'item1'), (1, 2, 'idem 1'),
       (2, 1, 'item2'),
       (3, 1, 'item3'), (3, 2, 'idem 3'),
       (4, 1, 'item4'), (4, 2, 'idem 4');

My expected output is :

在此处输入图片说明

This is what I have tried :

select 
    lang_id,
    case when lang_id = 2 AND itemI18N.item_text is not null then itemI18N.item_text
        when lang_id = 1 then itemI18N.item_text
    end as ite_texte
from 
    tbl_item_i18n itemI18N
group by 
    itemI18N.item_id, lang_id, itemI18N.item_text

But it does not give me expected result.

Purpose :- I would like to retrieve data for lang_id = 2 . If the record for lang_id = 2 does not exist, then retrieve data for lang_id = 2 .
How do I retrieve data using aggregate function?

LEFT JOIN Bring all the column with lenguaje 1, and null if doesnt have lenguaje 2.

I include extra column so you understand the result.

SELECT 
    item_id, 
    CASE 
       WHEN B.lang_id IS NULL THEN A.item_text
       ELSE B.item_text
    END as item_name,
    A.*
    B.*
FROM tbl_item_i18n A
LEFT JOIN tbl_item_i18n B
   ON A.item_id = B.item_id
  AND A.lang_id < B.lang_id

NOTE

Maybe need especial consideration if more than 2 lenguajes.

Another solution

SELECT *
FROM 
  (
    SELECT item_id, lang_id, item_text as item_name, 
            ROW_NUMBER() over (partition by item_id order by lang_id desc) as RN
   FROM tbl_item_i18n
  ) as t 
WHERE RN = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM