sql server 2008查询需要帮助

时间:2014-07-31 09:59:23

标签: sql sql-server-2008

我有这个表结构:

 ProductID  ProductName ParentId
    13       Test            NULL
    NULL     Test1           14
    13       Test2           14
    14       Test4           15 
    NULL     Test5           16

现在我想根据Parentid检索结果

  • 场景1:对于Parentid 14我希望行与productid = 13
  • 场景2:对于Parentid = 15我想要行与productid = 14
  • 场景3:-for Parentid = 16我想要productid的行为null

请帮我这样做

输出应该是

如果我通过parentid = 14然后o / p

13       Test2  14

如果我通过parentid = 15,那么

14       Test4  15

如果我通过parented = 16,那么

NULL     Test5  16

3 个答案:

答案 0 :(得分:0)

您可以在CASE条件中使用WHERE语句,例如

select ProductID,
  ProductName,
  ParentId
FROM products
WHERE ISNULL(ProductID,0) = CASE 
                  WHEN ParentId = 14 THEN 13 
                  WHEN ParentId = 15 THEN 14
                  ELSE 0 
                  END

答案 1 :(得分:0)

根据问题和情节,我假设显示带有ParentID输入参数的记录

SQL DEMO

SELECT t.* FROM tabletest t 
WHERE EXISTS (SELECT t1.ProductId 
              FROM tabletest t1 
              WHERE ISNULL(t1.ProductID, '') = ISNULL(t.ProductID, ''))
AND ParentID = 14

SELECT t.* FROM tabletest t 
WHERE EXISTS (SELECT t1.ProductId 
              FROM tabletest t1 
              WHERE ISNULL(t1.ProductID, '') = ISNULL(t.ProductID, ''))
AND ParentID = 15

SELECT t.* FROM tabletest t 
WHERE EXISTS (SELECT t1.ProductId 
              FROM tabletest t1 
              WHERE ISNULL(t1.ProductID, '') = ISNULL(t.ProductID, ''))
AND ParentID = 16

我不确定这是否是正确的查询实现,但根据问题,它会切断获取数据的目的。

答案 2 :(得分:0)

可能是这样的

SELECT ProductID,ProductName,ParentId
FROM products
WHERE ProductID IN (SELECT ProductId FROM products WHERE ParentId = 14);

SELECT ProductID,ProductName,ParentId
FROM products
WHERE ProductID IN (SELECT ProductId FROM products WHERE ParentId = 15);

SELECT ProductID,ProductName,ParentId
FROM products
WHERE ISNULL(ProductID,'') IN (SELECT ISNULL(ProductId,'') FROM products WHERE ParentId = 16);

FIDDLE DEMO