是否可以为count >=3,4,5,6,7,8
等执行以下操作
而不是为每个计数类别重复整个代码
Insert into OnePlus (SELECT DISTINCT Id, Name, COUNT(DISTINCT StartDate) AS OnePlusDays
FROM DataTable
HAVING OnePlusDays >= 1
GROUP BY Id, Name)
Insert into TwoPlus (SELECT DISTINCT Id, Name, COUNT(DISTINCT StartDate) AS TwoPlusDays
FROM DataTable
HAVING TwoPlusDays >= 2
GROUP BY Id, Name)
最后
SELECT Id, Name, "1+" AS Categories
FROM OnePlus
UNION
SELECT Id, Name, "2+" AS Categories
FROM TwoPlus
答案 0 :(得分:0)
你只在标签中提到sql。根据MySql或SQL Server,您可能需要更改转换/转换和连接。但这个查询可能有所帮助。你真的不需要将一个区别放在一个组中,你正在分组,这意味着只有不同的值,它们的计数才会被提取。
当然,表OnePlus,实际上就是你所谓的类别。
Insert into OnePlus
SELECT Id, Name, convert(varchar(10), COUNT(DISTINCT StartDate) ) + "+" AS Categories
FROM DataTable
GROUP BY Id, Name
答案 1 :(得分:0)
在T-SQL中,您可以写为:
SELECT Id,
NAME , -- make sure you write case statement in desc order
CASE WHEN PlusDays > = 2 THEN '2+'
WHEN PlusDays > = 1 THEN '1+' END AS Categories
FROM
(
SELECT DISTINCT Id, Name, COUNT(DISTINCT StartDate) PlusDays
FROM @DataTable
GROUP BY Id, Name
) AS T
ORDER BY Id asc