【问题标题】:How to select data from the following table?如何从下表中选择数据?
【发布时间】:2016-08-11 11:02:06
【问题描述】:

表格数据为:

如何获得结果为:

【问题讨论】:

  • 包含一些代码,显示您到目前为止所尝试的内容。
  • @Pooja-G 你无法确定我的输出是否正确。我在这里问了那个输出。我自己得到了输出,我在下面发布了

标签: sql sql-server sql-server-2008


【解决方案1】:

您的预期输出导致混乱。我以为您期望以下格式作为输出。

DECLARE @CategoriesDetails TABLE (category_code INT, parent_code INT, category_name VARCHAR(100));

INSERT INTO @CategoriesDetails (category_code, parent_code, category_name) VALUES
(1, 0, 'Food'),
(2, 1, 'Bakery'),
(3, 2, 'Snaks');

SELECT  C1.category_name AS [Sub category], 
        ISNULL(C2.category_name, '') AS [Parent category]
FROM @CategoriesDetails C1
LEFT JOIN @CategoriesDetails C2 ON C2.category_code = C1.parent_code

输出:

Sub category    Parent category
--------------------------------
Food            
Bakery          Food
Snaks           Bakery

【讨论】:

    【解决方案2】:

    你需要LEFT JOIN自己如下。

    SELECT  
        T.categroy_name,
        COALESCE(Parent.category_name, '') AS 'parent category'
    FROM
        Tbl T LEFT JOIN 
        Tbl Parent ON T.parent_code = Parent.categrory_code
    

    【讨论】:

      【解决方案3】:
      select category_name,parent_category_name from tbl_product p
      
      left join 
      (
          select cp.category_code, 
              case
                  when
                      cp.parent_code = 0 then ''
                  when
                      cp.parent_code != 0 then cp.category_name
              end as category_name,
              cp.parent_code, isnull(ch.category_name, cp.category_name) as parent_category_name from tbl_category cp
              left join 
              (
                  select cl.category_name, cl.category_code, cl.parent_code from tbl_category cl
              ) ch on cp.parent_code = ch.category_code
      ) as cat
       on cat.category_code = p.category_code
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-12
        • 2020-04-26
        • 2017-03-08
        • 2017-01-11
        • 1970-01-01
        • 2011-06-21
        相关资源
        最近更新 更多