With this data:
id | month | 2015 | 2014 | 2013
1 | january | 2 | 4 | 6
2 | february | 10 | 12 | 14
3 | march | 16 | 18 | 20
I have vb.net code here
Dim asd As Double = 2015
Dim msg As Double
sql = "select " & asd & " from tbl_coll_penalty where month = 'february'"
sda = New NpgsqlDataAdapter(sql, pgConnection)
sda.Fill(DS, "t")
msg = DS.Tables("t").Rows(0)(0).ToString()
MessageBox.Show(msg)
I got wrong answer with this code because the answer of this code is "2015" but I expect the answer to be "10". Can someone help me the proper code of this?
In PostgreSQL, your column name "2015" is interpreted as a literal value. So when you submit the query:
SELECT 2015 FROM tbl_coll_penalty ...
you simply get the value 2015 back.
In the SQL standard, a column identifier cannot start with a numeral (0..9). Check the documentation here. To have PostgreSQL interpret the string "2015" as a column name, you should double-quote it:
sql = "select """ & asd & """ from tbl_coll_penalty where month = 'february'"
Related
Any time the listbox in MS-Access receives data, it will automatically consider commas, semi-colons or other types of delimiters and separate the values into columns within the listbox.
Therefore, when I format the values to currency the comma it finds in $2,000 (for example) gets delimited to $2 (in column 1) and 000 (in column 2).
I did set column count to 4, so I see why it is doing that but there must be a different way...
I set the column count to 4 because I have 4 values that I want displayed in the list box.
List40.ColumnCount = 4
List40.AddItem (strProduct & ";" & mQty & ";" & format(uPricing,"Currency") & ";" & format(tPricing,"Currency"))
In summary I expect my list to look like this
+---------+----------+-----------+-----------+
| PRODUCT | QUANTITY | UNITPRICE | TOTALCOST |
+---------+----------+-----------+-----------+
| abc | 5 | $500.00 | $2,500.00 |
+---------+----------+-----------+-----------+
Instead I see:
+---------+----------+-----------+-----------+
| PRODUCT | QUANTITY | UNITPRICE | TOTALCOST |
+---------+----------+-----------+-----------+
| abc | 5 | $500.00 | $2 |
+---------+----------+-----------+-----------+
Enclose the value between double quotes (ASCII code 34):
.....& ";" & Chr(34) & format(tPricing,"Currency") & Chr(34))
I have a column that contains multiple word strings. Like this:
+---+-------------------------------+--------------+-------------------------------+--------------+-------------------------------+-------------------------------+
| | A | B | C | D | E | F |
+---+-------------------------------+--------------+-------------------------------+--------------+-------------------------------+-------------------------------+
| 1 | Early Summer Lawn Application | Service Call | Early Summer Lawn Application | Grub Control | Early Summer Lawn Application | Early Summer Lawn Application |
+---+-------------------------------+--------------+-------------------------------+--------------+-------------------------------+-------------------------------+
My question is how can I insert a comma after each word in the column, to end up with:
+---+-------------------------------+--------------+-------------------------------+--------------+-------------------------------+-------------------------------+
| | A | B | C | D | E | F |
+---+-------------------------------+--------------+-------------------------------+--------------+-------------------------------+-------------------------------+
| 1 | Early,Summer,Lawn,Application | Service,Call | Early,Summer,Lawn,Application | Grub,Control | Early,Summer,Lawn,Application | Early Summer Lawn Application |
+---+-------------------------------+--------------+-------------------------------+--------------+-------------------------------+-------------------------------+
Its ok to lose the space between the words and its ok if the results are in a different column, I just don't know how to insert the commas.
Won't a simple replace work here?
=replace(A1," ", ",")
replaces space with comma. The other function is
=substitute(A1, " ", ",")
also works, but substitute has another argument that might come in handy. It specifies which occurrence to substitute. For example, if you only wanted to replace the first blank space with comma but leave other blank spaces as is, then try this:
=substitute(A1, " ", ",", 1)
Bottom line, use replace if you know where to replace (position), and use substitute if you know what to replace (content). Either would work for a narrow class of problems as you discovered.
The following example erplaces programmatically all spaces with commas:
Sub example()
Dim s1 As String, s2 As String
Dim pos As Integer
s1 = ActiveSheet.ActiveCell.Value
s2 = ""
pos = InStr(1, s1, " ")
While (pos <> 0)
s2 = s2 & Mid(s1, 1, pos - 1) & ","
s1 = Mid(s1, pos + 1)
pos = InStr(1, s1, " ")
Wend
s2 = s2 & s1
ActiveSheet.ActiveCell.Value = s2
End Sub
At the moment, I cannot use a typical database so am using excel temporarily. Any ideas?
The
You have 3 dimensions here: dim1 (ABC), dim2 (123), dim3 (XYZ).
Here is how you make a cartesian product of 2 dimensions using standard Excel and no VBA:
1) Plot dim1 vertically and dim2 horizontally. Concatenate dimension members on the intersections:
2) Unpivoting data. Launch pivot table wizard using ALT-D-P (don't hold ALT, press it once). Pick "Multiple consolidation ranges" --> create a single page.. --> Select all cells (including headers!) and add it to the list, press next.
3) Plot the resulting values vertically and disassemble the concatenated strings
Voila, you've got the cross join. If you need another dimension added, repeat this algorithm again.
Cheers,
Constantine.
Here is a very easy way to generate the Cartesian product of an arbitrary number of lists using Pivot tables:
https://chandoo.org/wp/generate-all-combinations-from-two-lists-excel/
The example is for two lists, but it works for any number of tables and/or columns.
Before creating the Pivot table, you need to convert your value lists to tables.
Using VBA, you can. Here is a small example:
Sub SqlSelectExample()
'list elements in col C not present in col B
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
con.Open "Driver={Microsoft Excel Driver (*.xls)};" & _
"DriverId=790;" & _
"Dbq=" & ThisWorkbook.FullName & ";" & _
"DefaultDir=" & ThisWorkbook.FullName & ";ReadOnly=False;"
Set rs = New ADODB.Recordset
rs.Open "select ccc.test3 from [Sheet1$] ccc left join [Sheet1$] bbb on ccc.test3 = bbb.test2 where bbb.test2 is null ", _
con, adOpenStatic, adLockOptimistic
Range("g10").CopyFromRecordset rs '-> returns values without match
rs.MoveLast
Debug.Print rs.RecordCount 'get the # records
rs.Close
Set rs = Nothing
Set con = Nothing
End Sub
Here's a way using Excel formulas:
| | A | B | C |
| -- | -------------- | -------------- | -------------- |
| 1 | | | |
| -- | -------------- | -------------- | -------------- |
| 2 | Table1_Column1 | Table2_Column1 | Table2_Column2 |
| -- | -------------- | -------------- | -------------- |
| 3 | A | 1 | X |
| -- | -------------- | -------------- | -------------- |
| 4 | B | 2 | Y |
| -- | -------------- | -------------- | -------------- |
| 5 | C | 3 | Z |
| -- | -------------- | -------------- | -------------- |
| 6 | | | |
| -- | -------------- | -------------- | -------------- |
| 7 | Col1 | Col2 | Col3 |
| -- | -------------- | -------------- | -------------- |
| 8 | = Formula1 | = Formula2 | = Formula3 |
| -- | -------------- | -------------- | -------------- |
| 9 | = Formula1 | = Formula2 | = Formula3 |
| -- | -------------- | -------------- | -------------- |
| 10 | = Formula1 | = Formula2 | = Formula3 |
| -- | -------------- | -------------- | -------------- |
| 11 | ... | ... | ... |
| -- | -------------- | -------------- | -------------- |
Formula1: IF(ROW() >= 8 + (3*3*3), "", INDIRECT(ADDRESS(3 + MOD(FLOOR(ROW() - 8)/(3*3), 3), 1)))
Formula2: IF(ROW() >= 8 + (3*3*3), "", INDIRECT(ADDRESS(3 + MOD(FLOOR(ROW() - 8)/(3) , 3), 2)))
Formula3: IF(ROW() >= 8 + (3*3*3), "", INDIRECT(ADDRESS(3 + MOD(FLOOR(ROW() - 8)/(1) , 3), 3)))
One* general formula to rule them all!
The result
The formula
MOD(CEILING.MATH([index]/PRODUCT([size of set 0]:[size of previous set]))-1,[size of current set])+1
This formula gives the index (ordered position) of each element in the set, where set i has a size of n_i. Thus if we have four sets the sizes would be [n_1,n_2,n_3,n_4].
Using that index one can just use the index function to pick whatever attribute from the set (imagine each set being a table with several columns one could use index([table of the set],[this result],[column number of attribute]).
Explanation
The two main components of the formula explained, the cycling component and the partitioning component.
Cycling component
=MOD([partitioning component]-1, [size of current set])+1
Cycles through all the possible values of the set.
The modulo function is required so the result will "go around" the size of the set, and never "out of bounds" of the possible values.
The -1 and +1 help us go from one-based numbering (our set indexes) to zero-based numbering (for the modulo operation).
Partitioning component
CEILING.MATH([index]/PRODUCT([size of set 0]:[size of previous set]):
Partitions the "cartesian index" in chunks giving each chunk an "name".
The "cartesian index" is just a numbering from 1 to the number of elements in the Cartesian Product (given by the product of the sizes of each set).
The "name" is just an increasing-by-chunk enumeration of the "cartesian index".
To have the same "name" for all indexes belonging to each chunk, we divide the "cartesian index" by the number of partitions and "ceil" it (kind of round up) the result.
The amount of partitions is the total size of the last cycle, since, for each previous result one requires to repeat it for each of this set's elements.
It so happens that the size of the previous result is the product of all the previous sets sizes (including the size of a set before the first so we can generalize, which we will call the "set 0" and will have a constant size of 1).
With screenshots
Set sizes
Prepared set sizes including the "Set0" one and the size of the Cartesian Product.
Here, the sizes of sets are:
"Set0": 1 in cell B2
"Set1": 2 in cell C2
"Set2": 5 in cell D2
"Set3": 3 in cell E2
Thus the size of the Cartesian product is 30 (2*5*3) in cell A2.
Results
Table structure _tbl_CartesianProduct with the following columns and their formulas:
Results:
Cartesian Index: =IF(ROW()-ROW(_tbl_CartesianProduct[[#Headers];[Cartesian Index]])<=$A$2;ROW()-ROW(_tbl_CartesianProduct[[#Headers];[Cartesian Index]]);NA())
concatenation: =TEXTJOIN("-";TRUE;_tbl_CartesianProduct[#[Index S1]:[Index S3]])
Index S1: =MOD(CEILING.MATH([#[Cartesian Index]]/PRODUCT($B$2:B$2))-1;C$2)+1
Index S2: =MOD(CEILING.MATH([#[Cartesian Index]]/PRODUCT($B$2:C$2))-1;D$2)+1
Index S3: =MOD(CEILING.MATH([#[Cartesian Index]]/PRODUCT($B$2:D$2))-1;E$2)+1
step "size of previous partition":
Size prev part S1: =PRODUCT($B$2:B$2)
Size prev part S2: =PRODUCT($B$2:C$2)
Size prev part S3: =PRODUCT($B$2:D$2)
step "Chunk name":
Chunk S1: =CEILING.MATH([#[Cartesian Index]]/[#[Size prev part S1]])
Chunk S2: =CEILING.MATH([#[Cartesian Index]]/[#[Size prev part S2]])
Chunk S3: =CEILING.MATH([#[Cartesian Index]]/[#[Size prev part S3]])
final step "Cycle through the set":
Cycle chunk in S1: =MOD([#[Chunk S1]]-1;C$2)+1
Cycle chunk in S2: =MOD([#[Chunk S2]]-1;D$2)+1
Cycle chunk in S3: =MOD([#[Chunk S3]]-1;E$2)+1
*: for the actual job of producing the Cartesian enumerations
A little bit code in PowerQuery could solve the problem:
let
Quelle = Excel.CurrentWorkbook(){[Name="tbl_Data"]}[Content],
AddColDim2 = Table.AddColumn(Quelle, "Dim2", each Quelle[Second_col]),
ExpandDim2 = Table.ExpandListColumn(AddColDim2, "Dim2"),
AddColDim3 = Table.AddColumn(ExpandDim2, "Dim3", each Quelle[Third_col]),
ExpandDim3 = Table.ExpandListColumn(AddColDim3, "Dim3"),
RemoveColumns = Table.SelectColumns(ExpandDim3,{"Dim1", "Dim2", "Dim3"})
in RemoveColumns
Try using a DAX CROSS JOIN. Read more at MSDN
You can use the expression CROSSJOIN(table1, table2) to create a cartesian product.
I have my excel sheet like this:
A | B
-----
0 | 2
0 | 3
0 | 4
0 | 5
0 | 6
0 | 7
1 | 8
1 | 9
1 | 10
1 | 11
1 | 12
2 | 13
2 | 14
...
How do I get the value of B for the last occurrence of each value in A?
The output is -
C | D
0 | 7
1 | 12
2 | 14
Is there an easy way of doing this? Thanks!
Assuming you already have 0, 1, 2 etc. listed in C1 down then use this formula In D1 copied down
=LOOKUP(C1,A:B)
Highlight the entire table.
On Data tab, in the Outline pane click the Subtotals button.
In the At change in... box, select A.
At the Use function box, select Max.
In the Add Subtotal to box make sure B has a check mark
Click OK.
Use the dashes to collapse each section.
That will avoid any programming or formulas and leave the data intact.
To get the last value in column A use this formula:
=INDEX(A:A, COUNTA(A:A), 1)
The following will get the last value in column B:
=INDEX(B:B, COUNTA(B:B), 1)
A sample using a macro:
Sub LastValueInB()
VarA = Range("A1").Value
VarB = Range("B1").Value
Output = ""
For i = 1 To 10
If Range("A" & i).Value = VarA Then
VarB = Range("B" & i).Value
Else
Output = Output + VarA & VarB & vbCrLf
VarA = Range("A" & i).Value
End If
Next i
MsgBox Output
End Sub
I have a table that is 200 columns wide and need to return the data of a specific row and column but I won't know the column until runtime. I can easily get the row I want into either a list, an individual strongly typed object, or an Array through LINQ but I can't for the life of me figure out how to find the column I need.
So For instance (on a smaller scale) my table looks like this
GrowerKey | day1 | day2 | day3 | day4 |
-----------------------------------------
3 | 1 | 3 | 2 | 2 |
4 | 6 | 1 | 9 | 1 |
5 | 8 | 8 | 2 | 4 |
and I can get the row I want with something simple like this
Dim CleanRecord As List(Of Grower_Clean_Schedule) = (From key In eng.Grower_Clean_Schedules
Where key.Grower_Key = Grower_Key).ToList
how do I then return only the value of a specific column of that row (like say the value stored in "day2") When I won't know which column until runtime?
Something like this (starting with CleanRecord which you defined in your question):
dim matchingRow = CleanRecord.First()
dim props = matchingRow.GetType().GetProperties( _
BindingFlags.Instance or BindingFlags.Public))
dim myReturnVal = (from prop in props _
where prop.Name = "day2" _
select prop.GetValue(matchingRow, Nothing).FirstOrDefault()
return myReturnVal