SQL Server Using CONCAT and COUNT Clause in a sub query [closed]

uqzxnwby  于 2023-06-21  发布在  其他
关注(0)|答案(1)|浏览(126)

Closed. This question needs details or clarity . It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post .

Closed 5 mins ago.
Improve this question

I had a typical error indicating:

Column 'Data.Product_Purchased' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

I tried counting the number of product purchased using the COUNT function which was successful but adding the CONCAT function brought out an error when indicating COUNT in a subquery. Code is below using (SQL query)

SELECT CONCAT('Product_Purchased', '-', 'No') Total_Product_Purchased
FROM
(
SELECT COUNT(Product_Purchased) Num, Product_Purchased
FROM Data
) A
GROUP BY Product_Purchased
bttbmeg0

bttbmeg01#

When you got your initial count you likely ran the following:

SELECT COUNT(Product_Purchased) Num, Product_Purchased
FROM Data
GROUP BY Product_Purchased

All of this must be contained within your subquery, but you, perhaps by accident, put your GROUP BY in the main query. Instead:

SELECT CONCAT('Product_Purchased', '-', 'No') Total_Product_Purchased
FROM
(
    SELECT COUNT(Product_Purchased) Num, Product_Purchased
    FROM Data
    GROUP BY Product_Purchased
) A;

This will no longer throw an error, but you still have a problem in that you are attempting to concatenate string-literals instead of columns returned in the subquery's result set. Instead:

SELECT CONCAT(Product_Purchased, '-', Num) Total_Product_Purchased
FROM
(
    SELECT COUNT(Product_Purchased) Num, Product_Purchased
    FROM Data
    GROUP BY Product_Purchased
) A;

Furthermore, the subquery is superfluous as you can do this all in the same query:

SELECT CONCAT(Product_Purchased, '-', COUNT(Product_Purchased)) Total_Product_Purchased
FROM Data
GROUP BY Product_Purchased

相关问题