我有一张如下图所示的表格。
View : Cat : Name
abcView
abcView abcCategory2
abcView abcCategory2 abcFilter
abcView2
abcView2 abcCategory
abcView2
abcView3
View是Cat的父级,Cat是Name的父级。如果Cat存在,View永远不会为空。同样,如果Name存在,Cat永远不会为空。我想以这样一种方式获取数据,我不希望在我的结果中有任何空格或复制。如果有两个条目,一个有孩子,一个没有孩子,那么我只想显示孩子的条目。但如果没有孩子,那么我只想返回父母的姓名。
View : Cat : Name
abcView abcCateogry2 abcFilter
abcView2 abcCategory
abcView3
答案 0 :(得分:1)
试试这个:
SELECT a.View, MAX(a.Cat) Cat, MAX(a.Name) AS `name`
FROM tableA a
GROUP BY a.View
答案 1 :(得分:0)
尝试以下查询并检查它是否正常工作。它正在处理样本数据,但可能会在表中的数据中产生问题。我正在组合三列并检查表中不存在相同的组合,因此您将获得一行最高级别:
DECLARE @TABLE TABLE
(
[View] VARCHAR(100),
Cat VARCHAR(100),
Name VARCHAR(100)
)
INSERT INTO @TABLE VALUES
('abcView','',''),
('abcView','abcCategory1',''),
('abcView','abcCategory2',''),
('abcView','abcCategory2','abcFilter'),
('abcView2','',''),
('abcView2','abcCategory',''),
('abcView2','',''),
('abcView3','','')
SELECT
t1.[View],
t1.Cat,
t1.Name
FROM
@TABLE AS t1
WHERE
(
SELECT
COUNT(*)
FROM
@TABLE
WHERE
([View]+'-'+Cat+'-'+Name) LIKE '%'+ REPLACE((t1.[View]+'-'+t1.Cat+'-'+t1.Name),'--','-') + '%'
) = 1
答案 2 :(得分:0)
您可以通过
选择名称所在的所有条目SELECT View, Cat, Name
FROM yourTable
WHERE Name NOT NULL
然后将它与所有条目联合起来,只存在一只猫(并且没有名字)
SELECT View, Cat, Name
FROM yourTable
WHERE Name IS NOT NULL
UNION
SELECT View, Cat, NULL
FROM yourTable
WHERE Cat IS NOT NULL AND
Name IS NULL AND
Cat NOT IN (SELECT Cat FROM yourTable WHERE Name IS NOT NULL)
最后将它与所有条目联合起来,只有一个视图(并且不存在名称和猫)
SELECT View, Cat, Name
FROM yourTable
WHERE Name IS NOT NULL
UNION
SELECT View, Cat, NULL
FROM yourTable
WHERE Cat IS NOT NULL AND
Name IS NULL AND
Cat NOT IN (SELECT Cat FROM yourTable WHERE Name IS NOT NULL)
UNION
SELECT View, NULL, NULL
FROM yourTable
WHERE View IS NOT NULL AND
Cat IS NULL AND
View NOT IN (SELECT View FROM yourTable WHERE Cat IS NOT NULL)