SQLite Group By with Order By not working - iphone

Need some stack overflow love. Read the other questions related to group by and sort by and those answers don't seem to work for me. I am not really strong in the finer details of db statements and think there is some dependency or conflict between group and order by statements I am missing.
I have a table (itemOptions) that holds all the options of an item and all the possible values for those options. Think multiple select/drop down boxes for an item and the list of values for each drop down. And unfortunately I can't change the db structure, as a web service is providing the sqlite file.
Here's the structure:
absTtemId optionName optionPosition valueName valuePosition
item1 size 1 small 1
item1 size 1 medium 2
item1 size 1 large 3
item1 color 2 white 1
item1 color 2 red 2
item1 color 2 yellow 3
item2 name 1 willis 1
item2 name 1 smith 2
item2 name 1 bowman 3
The query needs to return optionsNames for a given item ordered by optionPosition, and then a list of valueNames for each option ordered by valueposition, like this
option valueNames
size small, medium, large
color white, red, yellow
I am able to get the grouping of valueNames by option to work, but when I try to add sorting anywhere, sqlite throws errors.
Here's my current sql statement that returns these results, however option and valueNames are never in order.
SELECT optionName, group_concat(valueName)
FROM itemOptions
WHERE absItemId = 'item1'
GROUP BY optionName
option valueNames
size medium, small, large
color yellow, red, white
Here's some of my failed attempts at adding sorting for valueName and optionName
SELECT optionName, group_concat(valueName ORDER BY valuePosition DESC)
FROM itemOptions
WHERE absItemId = 'item1'
GROUP BY optionName
EDIT: sporting for optionName grouping is working now with this. Only valueName sorting within the group_concat not working.
SELECT optionName, group_concat(valueName)
FROM itemOptions
WHERE absItemId = 'item1'
GROUP BY optionName
ORDER BY optionPosition

try
SELECT a.optionName, group_concat(a.valueName)
FROM (SELECT * FROM itemOptions ORDER BY valuePosition ASC) As a
WHERE a.absItemId = 'item1'
GROUP BY a.optionName
ORDER BY a.optionName

Related

How to compare values of two columns in Postgresql

I need to compare two columns which has below values and get a consolidated value in PostgreSQL. For an Id value, if all is green OR red, I want GREEN or RED to be returned respectively and even if one is RED, I want RED to be returned. Can someone please help? Thanks
ID STATUS
1 GREEN
1 GREEN
1 RED
2 GREEN
2 GREEN
2 GREEN
You seem to want string aggregation:
select id, string_agg(distinct status, ' or ' order by status) statuses
from mytable
group by id
If you want a single value returned, with priority given to "RED", then:
select id, max(status)
from mytable
group by id
This works because, string-wise, "RED" is greater than "GREEN". You don't specify what to do if there are more than two columns, so the answer does not address that.

How can i make this mysql query ? If possible at all

I have this table
itemname property value
------------------------------------------
A size big
A color red
B size big
B color blue
C size small
C color blue
D size small
D color blue
E size small
E color blue
Im creating a list like this: SELECT property,value,COUNT(itemname),GROUP_CONCAT(itemname) FROM table GROUP BY property,value
property value count
---------------------------------
size big 2 (A,B)
size small 3 (C,D,E)
color red 1 (A)
color blue 4 (B,C,D,E)
I want to filter the items which are BIG && SMALL && BLUE, how can i achieve this result ? (I MUST be specific about the property when addressing a value for filtering)
`SELECT
property,value,COUNT(itemname),GROUP_CONCAT(itemname)
FROM
table
GROUP BY
property,value
HAVING
( property IN ('size') && value IN ('big','small') )
&&
( property IN ('color') && value IN ('blue') )`
But this has no result, because it tries to match the row with size and color at the same time ? My desired output in this case is to avoid the item A because it is red, like this:
property value count
---------------------------------
size big 1 (B) A not here, because it is red
size small 3 (C,D,E) no change because all are blue
color red 0 (A) no red is selected, so this row should be 0 or not listed at all
color blue 4 (B,C,D,E) all the 4 are big or small and blue
Please someone help me out in this, i lost 2days wondering on the solution.
I might use CASE combined with HAVING ? Or i should address the WHERE instead somehow ?
Note: This table is actually not real, but if this question can be solved i can use it in my real tables which are a lot more complicated.
I figured a solution on my own, of course this example table is nonsense, the point is the way it had been solved.
`
SELECT
property,
value,
COUNT(t.itemname) AS count
FROM (
SELECT
itemname
FROM
table
GROUP BY
itemname
HAVING
COUNT (CASE WHEN property='size' AND value IN ('big','small') THEN 1 END) >=1
&&
COUNT (CASE WHEN property='color' AND value IN ('blue') THEN 1 END) >=1
) t
INNER JOIN
table ON table.itemname=t.itemname
GROUP BY
property,value
`

Crystal report - Grouping from Formula and Running Totals

I am trying to create a Crystal Report. One of the parameters that it has, is a Boolean flag which change the groupings of the Report.
What I'm trying to do is to add 3 levels of grouping from a formula.
The code that I wrote is:
if {?summarized_detailed} = true then
'Store Code : ' + {SNV_SP_ProfitabilityAndBreakEvenPerStore;1.WhsCode}
else
if {?season_supplier} = true then
'Store Code : ' + {SNV_SP_ProfitabilityAndBreakEvenPerStore;1.WhsCode} + ChrW(10) + 'Season : ' + {SNV_SP_ProfitabilityAndBreakEvenPerStore;1.SEASON} + ChrW(10) + 'Brand : ' + {SNV_SP_ProfitabilityAndBreakEvenPerStore;1.BRAND}
else
'Store Code : ' + {SNV_SP_ProfitabilityAndBreakEvenPerStore;1.WhsCode} + ChrW(10) + 'Supplier : ' + {SNV_SP_ProfitabilityAndBreakEvenPerStore;1.CardCode} + ChrW(10) + 'Brand : ' + {SNV_SP_ProfitabilityAndBreakEvenPerStore;1.BRAND}
{?summarized_detailed} is the parameter (the flag for grouping).
if he chooses true, the report must have the columns -> Store Code , Season or Supplier (it based on another flag-parameter) and Brand.
Output Layer that I have :
Name of Col1 Name of Col2 Name of Col3
Store: Value for Store Code, Season or Supplier: Value for Season or Supplier, Brand: Value for Brand | total Brand Col1 total Brand Col2 total Brand Col3 ....
With this Code, I take the result that I want. All database's rows are separated according to those groups.
The problem is, that I want to have total sum for every column that I have in my report. But I can't do this, because the above formula, created only ONE union group. So, I can have a summary only for the details within every brand.
Output Layer that I want :
Name of Col1 Name of Col2 Name of Col3
Store: Value for Store Code |
Seas or Sup: Value for Season or Supplier |
Brand: Value for Brand | total Brand Col1 total Brand Col2 total Brand Col3
//when supplier or season within all groups changes (not included in report)
--------------------------------------------------------------------------------------------
Total Supplier or Season: total Sup/Season Col1 total Sup/Season Col2 total Sup/Seas Col3
//when store within all groups changes (not included in report)
Total Store: total Store Col1 total Store Col2 total Store Col3
---------------------------------------------------------------------------------------------
With total Brand Col1 I want to do a summary for all rows of details for each field of the same brand.
With total Supplier Col1 I want to sum all total Brands for each field of the same supplier.
With total Store Col1 I want to sum all total Suppliers for each field for every shop.
How can I compute those totals and display them only when Season or Supplier changes, and when Store changes with no regarding the change of the union Group ?
Or is there an easier and better way to make those 3 groups from formula according to the parameter but let them be separated so that I can control them and do my summarizes ?
This is how I handle this type of requirement:
If you want a maximum of 3 groups, but potentially less, then you need to create two different formula fields. In the report design, you set grouping to group on Store_Code first, then the other two formula fields.
If the refresh/runtime parameter will be FALSE for when you want the three-level grouping, then the formulas should look something like this:
Group1_Formula1: if {?param} = TRUE then '' else {Season}
Then the next:
Group2_Formula: if {?param} = TRUE then '' else {Brand}
If you want totals/subtotal the just place them as summary fields in the group headers, with conditional display to suppress them as necessary.
The result will be that, even though grouping on all three levels is always taking place, for the subgroups below the always-active "Store_Code" each subgroup will have only a single group of all records if the {?Param} = TRUE, effectively meaning there is no grouping happening.
One caveat: This presumes you aren't using print-time evaluation, e.g. before/after printing, etc., in any of the related formulas necessary to perform your grouping.

Retrieve field based on record field

I have 3 tables
items,
item_units,
order_items
First table items has the list of items that can be ordered.
Second table item_units has units for the items as well as the amount of those items in this unit
Third table has items that were ordered... ie... item_code , unit, qty
Here are the columns for items
[item_code]
,[desc]
Here are the columns for item_units
,[item_code]
,[unit]
,[amount]
,[price]
,[default_sprd_sht]
Here are the columns for order_items
,[order_id]
,[item_code]
,[item_desc]
,[unit]
,[qty]
,[price]
Note the [default_sprd_sht]. This field is a boolean. If it's set to true this unit is never put into order_items table. This field will be used as calculation field.
For example:
If 1 customer orders 2 6 packs of bread and another orders 3 dozens of bread, the baker needs to know how many pans of bread to make.
Now a 6 pack unit has 6 breads as amount, meaning 2 * 6 = 12. And a dozen unit has 12 breads.. 12 * 3 = 36. A pan bread unit has 20 breads. So i need to add up all the bread units amounts and divide them by the pan amount like so
((2*6) + (12 * 3)) / 20 = 2.4
So the first thing I did to create a report for the baker was
Create a group for order_items.item_code and then order_item.unit.
This needs to be done since the same item and unit cobination will be repeated in different orders. The baker needs to see how many bagels or breads he needs to bake in total.
in the order_item.unit group header I created a formula field that multiplies the order_item.unit by item.amount
Sum ({order_items.qty}, {order_items.unit}) * {items_units.amount}
That was easy.
But I aslo need to group all order items if there exists a record in the items_units with the same item_code and with [default_sprd_sht] set to true
This would look like so
(Sum ({order_items.qty}, {order_items.unit}) * {items_units.amount}) / (get amount for unit with the same item_code and [default_sprd_sht] = 1)
I have two problems accomplishing this.
How to check if this order item has a unit with same item_code and
[default_sprd_sht] = 1?
How to further group order items only if there is a unit with same
item_code and [default_sprd_sht] = 1?

how to get grouped query data from the resultset?

I want to get grouped data from a table in sqlite. For example, the table is like below:
Name Group Price
a 1 10
b 1 9
c 1 10
d 2 11
e 2 10
f 3 12
g 3 10
h 1 11
Now I want get all data grouped by the Group column, each group in one array, namely
array1 = {{a,1,10},{b,1,9},{c,1,10},{h,1,11}};
array2 = {{d,2,11},{e,2,10}};
array3 = {{f,3,12},{g,3,10}}.
Because i need these 2 dimension arrays to populate the grouped table view. the sql statement maybe NSString *sql = #"SELECT * FROM table GROUP BY Group"; But I wonder how to get the data from the resultset. I am using the FMDB.
Any help is appreciated.
Get the data from sql with a normal SELECT statement, ordered by group and name:
SELECT * FROM table ORDER BY group, name;
Then in code, build your arrays, switching to fill the next array when the group id changes.
Let me clear about GroupBy. You can group data but that time its require group function on other columns.
e.g. Table has list of students in which there are gender group mean Male & Female group so we can group this table by Gender which will return two set . Now we need to perform some operation on result column.
e.g. Maximum marks or Average marks of each group
In your case you want to group but what kind of operation you require on price column ?.
e.g. below query will return group with max price.
SELECT Group,MAX(Price) AS MaxPriceByEachGroup FROM TABLE GROUP BY(group)