我已经返回了如下所示的行:
2 - Eggs
3 - Bacon
4 - Bacon Smoked
我想按'%Bacon%'分组,以便我的点数为2
。
我该怎么做才是SQL?
我应该看到这样的结果:
Eggs - 1
Bacon - 2
答案 0 :(得分:1)
以下内容(Demo):
SELECT 'Eggs' AS Category, COUNT(*) AS MyCount
FROM MyTable
WHERE MyField LIKE '%Eggs%'
UNION ALL
SELECT 'Bacon' AS Category, COUNT(*) AS MyCount
FROM MyTable
WHERE MyField LIKE '%Bacon%'
答案 1 :(得分:1)
其他解决方案:
SELECT
Eggs = SUM(CASE WHEN FoodColumn LIKE '%Eggs%' THEN 1 ELSE 0 END),
Bacon = SUM(CASE WHEN FoodColumn LIKE '%Bacon%' THEN 1 ELSE 0 END)
FROM Test
您可以看到演示here。
如果您需要将结果分成两个单独的行
SELECT *
FROM
(
SELECT
Eggs = SUM(CASE WHEN FoodColumn LIKE '%Eggs%' THEN 1 ELSE 0 END),
Bacon = SUM(CASE WHEN FoodColumn LIKE '%Bacon%' THEN 1 ELSE 0 END)
FROM Test
) AS Test
UNPIVOT
(
Quantity FOR Foods IN (Eggs, Bacon)
) AS Result
您可以看到演示here。
答案 2 :(得分:1)
未经测试,但我认为它应该可行
SELECT COUNT(*) as QTY, RS.FOOD_TYPE
FROM
(SELECT
Case patIndex ('%[ /-]%', LTrim (FOOD_TYPE))
When 0 Then LTrim (FOOD_TYPE)
Else substring (LTrim (FOOD_TYPE), 1, patIndex ('%[ /-]%', LTrim (FOOD_TYPE)) - 1)
End FOOD_TYPE
FROM YOUR_TABLE) RS
GROUP BY RS.FOOD_TYPE
答案 3 :(得分:0)
create table MyTable
(id int, FieldName varchar(50) )
insert into MyTable values (1, 'Eggs')
insert into MyTable values (2, 'Bacon')
insert into MyTable values (3, 'Bacon Smoked')
select count(FieldName), FieldName from (
select
case
when charindex('eggs', FieldName) > 0 then 'eggs'
when charindex('bacon', FieldName) > 0 then 'bacon'
end as FieldName
from MyTable) as myMyTablealias
group by FieldName
答案 4 :(得分:0)
这是一个非常具体的案例..你能提供更多数据吗?无论如何这有用吗?
with list (item) as (
select
item
from (
values
('Eggs'),
('Bacon'),
('Bacon Smoked')) list (item)
)
select
LEFT(item,
(case
when CHARINDEX(' ',item,1) = 0
then LEN(item)
else CHARINDEX(' ',item,1) end)
) filtered,
COUNT(*)
from list
group by
LEFT(item,
(case
when CHARINDEX(' ',item,1) = 0
then LEN(item)
else CHARINDEX(' ',item,1) end))