SQL Server UNION ALL for several subqueries takes a long time

nfg76nw0  于 2023-05-05  发布在  其他
关注(0)|答案(2)|浏览(186)

I'm trying to count several items in the same table below:
| food |
| ------------ |
| apple cider |
| cake manzana (manzana in spanish == apple) |
| carrot cake |
| banana pudding |

I want end up with the following table:

foodcount
apple2
carrot1
banana1

I tried the following query which works for counting the apples:

SELECT 'apple' as placeholder, COUNT(*)
FROM table WHERE (food LIKE '%apple%' OR food LIKE '%manzana%') and date > '10/10/2021'

The issue is that when I try to expand it to get all of the food items together, it takes a long while:

SELECT 'apple' as placeholder, COUNT(*) FROM table WHERE (food LIKE '%apple%' OR food LIKE '%manzana%') and date > '10/10/2021' and ...
UNION ALL
SELECT 'carrot' as placeholder, COUNT(*) FROM table WHERE food LIKE '%carrot%'  and date > '10/10/2021' and ...
UNION ALL
SELECT 'banana' as placeholder, COUNT(*) FROM table WHERE food LIKE '%banana%' and date > '10/10/2021' and ...

Any other way to construct this query?

ars1skjm

ars1skjm1#

Load the foods you're looking for into a temp table, then join with LIKE :

CREATE TABLE #findfood (food_to_find nvarchar(50));

INSERT INTO #findfood (food_to_find)
VALUES ('apple'),('carrot'),('banana');

CREATE TABLE #food (food_name nvarchar(100));

INSERT INTO #food (food_name)
VALUES ('apple cider'),('cake apple'),('carrot cake'),('banana pudding');

SELECT food_to_find, COUNT(*) AS count_food_name
FROM #findfood
    INNER JOIN #food ON #food.food_name LIKE '%' + #findfood.food_to_find + '%'
GROUP BY food_to_find;
food_to_findcount_food_name
apple2
banana1
carrot1
c9qzyr3d

c9qzyr3d2#

Why don't you do :

SELECT CASE WHEN food LIKE '%apple%' THEN 'apple'
            WHEN food LIKE '%carrot%' THEN 'carrot'
            WHEN food LIKE '%banana%' THEN 'banana' END AS placeholder, COUNT(*) 
FROM   Atable 
WHERE  dates > '2021-01-01' ---
GROUP  BY CASE WHEN food LIKE '%apple%' THEN 'apple'
            WHEN food LIKE '%carrot%' THEN 'carrot'
            WHEN food LIKE '%banana%' THEN 'banana' END

--> example :

CREATE TABLE Atable (food VARCHAR(32), dates date);

INSERT INTO Atable VALUES
('qsqszcbananasqwdcqdesc', '2022-01-01'), 
('qsdvdszcbananasqwdcqdeqfeqsdc', '2022-01-01'), 
('qsqszccarrotsqwdcqdesc', '2022-01-01');

--> results :

placeholder (Aucun nom de colonne)
banana      2
carrot      1

相关问题