> ID ProductID OptionName OptionValue SKU
>
> 1 709 Title Como test
> 2 709 Color Cobalt test
> 3 709 Color Crimson RNA.331.02.MM1K
> 4 709 Title Como G2 RNA.331.02.MM1K
> 7 709 Color another color test ipn
> 8 709 Title another title test ipn
From the above table i want the following
Select distinct OptionName from myTable where ProductID = 709 group by OptionValue
but sql server is giving error on the group by clause and dont know how can i have all the different values grouped to distinct OptionName?
or i just can not ?
the result i want is as follows
[0] => array
[Color] => array
[0] => Cobalt test
[1] => Crimson
[2] => another color
[Title] => array
[0] => Como test
[1] => Como G2
[2] => another title
You need to use an aggregate function on the fields (like FIRST(), LAST(), MAX(), AVG() ...) you are selecting when you have a GROUP BY-clause. Also, distinct is not necessary when you have GROUP BY. Can you explain what data you want to extract and not only post a faulty query?
EDIT :
SELECT OptionName, OptionValue FROM myTable WHERE ProductID = 709 ORDER BY OptionName ASC
Will produce this:
> OptionName OptionValue
>
> Color Cobalt test
> Color Crimson
> Color another color
> Title Como test
> Title Como G2
> Title another title
Converting to arrays etc. is something you have to do in your application, not with SQL.
Here is one solution
Select OptionName from myTable where ProductID = 709 limit 1
why does group by have an underscore
Try it without the distinct and with the OptionValue
in there
select OptionName
from myTable
where ProductID = 709
group by OptionName, OptionValue
Using the GROUP BY will give you the distinct combinations.
By using GROUP BY OptionValue
you're saying this...
- Get all the records from my query as normal
- Group records up that have the same OptionValue
- Return only one record for each of those groups
In your case, you then try to return the OptionName. This is a problem because there are multiple OptionName's to display per group, but only one record to do so per group.
As has been said, the right Query depends on what you need, and I'm not 100% clear on that from what you have written. (Giving an example of the results you need, and how to get those results, would help.)
My guess is that you just want two records ( Color
and Title
). If so you can do either of these...
SELECT DISTINCT OptionName FROM myTable WHERE ProductID = 709
SELECT OptionName FROM myTable WHERE ProductID = 709 GROUP BY OptionName
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.