I'm trying to make multiple values "Bold" within an expression when the value contains "x". Html Placeholder properties doesn't meet my need and I'm struggling to get it working with the below as there are multiple statements in my expression:
=(IIF(Fields!Test1.Value="x", "Bold", "Normal") OR (Fields!Test2.Value="x", "Bold", "Normal") etc etc
I think I need to create a custom code function then call the function where needed in the expression but I haven't a clue where to start! Any help would be greatly appreciated.
Update:
Switch is working but bolding whole expression not just values specified within Placeholder Properties of expression. I believe this is because my main expression has concatenated fields creating one long string.
Placeholder exp
Result
Value exp
+-----------+------------+-----------+------------------+------------------+-----------+-----------+------------+-----------+-------------------+---------+--------------+-----------+----------------+-------------------------------+-----------------+---------------+--------------+----------+------------------+------------------+------------------+------------------+------------+---+------------+-----------+-------------------+-----------+--------------+-----------+----------------+---------+----------+-------------------+----------------------+---------------+----------------+---------+
| id_number | first_name | last_name | pref_address_ind | h_addr_type_code | h_care_of | h_street1 | h_street2 | h_street3 | h_foreign_cityzip | h_city | h_state_code | h_zipcode | h_country_code | h_email_address | p_email_address | h_phone | | hc_phone | b_company_name_1 | b_company_name_2 | b_business_title | fld_of_work_code | b_street1 | | b_street2 | b_street3 | b_foreign_cityzip | b_city | b_state_code | b_zipcode | b_country_code | b_phone | bc_phone | b_email_address | | full_business | pref_email_ind | Main_ID |
+-----------+------------+-----------+------------------+------------------+-----------+-----------+------------+-----------+-------------------+---------+--------------+-----------+----------------+-------------------------------+-----------------+---------------+--------------+----------+------------------+------------------+------------------+------------------+------------+---+------------+-----------+-------------------+-----------+--------------+-----------+----------------+---------+----------+-------------------+----------------------+---------------+----------------+---------+
| 165815 | Test | Test1 | NULL | | NULL | NULL | x Apt #09 | NULL | NULL | NULL | NULL | NULL | x USA | NULL | NULL | DELETED | | DELETED | NULL | ~ | NULL | NULL | NULL | | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | | NULL | NULL | 165815 |
| 165816 | Test | Test2 | NULL | | NULL | Street | x Street 1 | x Street2 | NULL | Houston | NULL | NULL | NULL | x Home Email:testing#test.com | NULL | x Home Phone: | 111-111-1111 | NULL | NULL | ~ | NULL | NULL | x Business | 1 | x Street 2 | NULL | NULL | x Houston | x TX | x 77777 | NULL | NULL | NULL | x Business Email: | btesting#testing.com | NULL | NULL | 165816 |
+-----------+------------+-----------+------------------+------------------+-----------+-----------+------------+-----------+-------------------+---------+--------------+-----------+----------------+-------------------------------+-----------------+---------------+--------------+----------+------------------+------------------+------------------+------------------+------------+---+------------+-----------+-------------------+-----------+--------------+-----------+----------------+---------+----------+-------------------+----------------------+---------------+----------------+---------+
There should be no need for custom code although depending on how complex the rules are you may want to consider SWITCH.
Based on your simple example you could do either of these
=IIF(
Fields!Test1.Value = "x" OR Fields!Test2.Value = "x",
"Bold",
Nothing)
or for a more complex situation
= SWITCH (
Fields!Test1l.Value = "x" OR Fields!Test2.Value="x", "Bold",
Feilds!Test3.Value = "Z" AND Fields!Test4.Value >10, "SemiBold",
True, Nothing)
SWITCH Evaluates each expression/result pair and stops when it hits the first that evalutes to True. The final 'True, Nothing' acts like an else. SWITCH if easier to read than nested IIFs but IIF can be simpler if the rules are simple.
UPDATE:
The following shows doing this using HTML generated in the dataset query. I know next to nothing about HTML this this may be fixable but here's where I got to ....
Based on your sample table I created a new column with a HTML version of the address using </p> to create the line breaks.
It also suppresses blank rows.
The sql looks something like
SELECT
HomeAddrFormattedP1 = '<p>Home Address: </p>'
+ IIF( ISNULL(h_street1,'')='', '', IIF( LEFT(h_street1,1) = 'x', '<b>' + h_street1 + '</b></p>', h_street1 + '</p>') )
+ IIF( ISNULL(h_street2,'')='', '', IIF( LEFT(h_street2,1) = 'x', '<b>' + h_street2 + '</b></p>', h_street2 + '</p>') )
+ IIF( ISNULL(h_street3,'')='', '', IIF( LEFT(h_street3,1) = 'x', '<b>' + h_street3 + '</b></p>', h_street3 + '</p>') )
+ IIF( ISNULL(h_foreign_cityzip,'')='', '', IIF( LEFT(h_foreign_cityzip,1) = 'x', '<b>' + h_foreign_cityzip + '</b></p>', h_foreign_cityzip + '</p>') )
+ IIF( ISNULL(h_city,'')='', '', IIF( LEFT(h_city,1) = 'x', '<b>' + h_city + '</b></p>', h_city + '</p>') )
+ IIF( ISNULL(h_state_code,'')='', '', IIF( LEFT(h_state_code,1) = 'x', '<b>' + h_state_code + '</b></p>', h_state_code + '</p>') )
+ IIF( ISNULL(h_zipcode,'')='', '', IIF( LEFT(h_zipcode,1) = 'x', '<b>' + h_zipcode + '</b></p>', h_zipcode + '</p>') )
+ IIF( ISNULL(h_country_code,'')='', '', IIF( LEFT(h_country_code,1) = 'x', '<b>' + h_country_code + '</b></p>', h_country_code + '</p>') )
,
*
FROM myTable
Using this as my report's dataset query I then added a simple table with 3 columns one for HomeAddrFormattedP1, first_name and last_name
All I did then was right-click the HomeAddrFormattedP1 placeholder and set its properties to Markup Type = HTML
This gave the following final result.
Related
From MySQL JSON data field, I'm extracting data from array like so:
SELECT
data ->> '$.fields[*]' as fields
FROM some_database...
which returns:
[{
"id": 111056,
"hint": null,
"slug": "email",
"label": "E-mail",
"value": null,
"field_value": "test#example.com",
"placeholder": null
}, {
"id": 111057,
"hint": null,
"slug": "name",
"label": "Imię",
"value": null,
"field_value": "Aneta",
"placeholder": null
}]
I can also extract single column:
SELECT
data ->> '$.fields[*].field_value' as fields
FROM some_database...
and that returns the following result:
[test#example.com, Aneta]
But how can I extract field_value alongside with label as key-pairs?
Preferred output would be a single multi-row string containing pairs:
label: field_value
label: field_value
...
Using example shown above it would get me following output:
E-mail: test#example.com
Imię: Aneta
One-liner preferred as I have multiple of such arrays to extract from various fields.
Here's an example of extracting the key names as rows:
select j.keyname from some_database
cross join json_table(
json_keys(data->'$[0]'),
'$[*]' columns (
keyname varchar(20) path '$'
)
) as j;
Output:
+-------------+
| keyname |
+-------------+
| id |
| hint |
| slug |
| label |
| value |
| field_value |
| placeholder |
+-------------+
Now you can join that to the values:
select n.n, j.keyname,
json_unquote(json_extract(f.data, concat('$[', n.n, ']."', j.keyname, '"'))) as value
from some_database as d
cross join json_table(
json_keys(d.data->'$[0]'),
'$[*]' columns (
keyname varchar(20) path '$'
)
) as j
cross join n
join some_database as f on n.n < json_length(f.data);
Output:
+---+-------------+------------------+
| n | keyname | value |
+---+-------------+------------------+
| 0 | id | 111056 |
| 0 | hint | null |
| 0 | slug | email |
| 0 | label | E-mail |
| 0 | value | null |
| 0 | field_value | test#example.com |
| 0 | placeholder | null |
| 1 | id | 111057 |
| 1 | hint | null |
| 1 | slug | name |
| 1 | label | Imię |
| 1 | value | null |
| 1 | field_value | Aneta |
| 1 | placeholder | null |
+---+-------------+------------------+
I'm using a utility table n which is just filled with integers.
create table n (n int primary key);
insert into n values (0),(1),(2),(3)...;
If this seems like a lot of complex work, then maybe the lesson is that storing data in JSON is not easy, when you want SQL expressions to work on the discrete fields within JSON documents.
You can use JSON_VALUE:
select JSON_VALUE (json_value_col, '$.selected_key') as selected_value from user_details ;
You can also use JSON_EXTRACT:
select JSON_EXTRACT (json_value_col, '$.selected_key') as selected_value from user_details ;
For more details refer:
https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html
A few days ago a colleague made this question: Order and group by with one column
It was resolved. A simple and clean query, very cool. The solution seemed to be worth it, except that we need to implement it in JPA.
As JPA does not accept subqueries in JOIN we had to do it as nativeQuery, but in doing so we have problems with paging, since JPA does not combine this with native queries.
https://docs.spring.io/spring-data/jpa/docs/1.8.0.M1/reference/html/
Native queriesThe #Query annotation allows to execute native queries
by setting the nativeQuery flag to true. Note, that we currently don’t
support execution of pagination or dynamic sorting for native queries
as we’d have to manipulate the actual query declared and we cannot do
this reliably for native SQL.
We have no idea how to continue with this.
What we have to do: we have a series of records with phone number, user and date, and each user has been able to call N times. We need to obtain all the records grouped by phone number and sorted (DESC) by the most recent date of each group of numbers.
e.g.:
With this data:
+--------------+---------------------+-------------+---------------+
| phone_number | registered | name | first_surname |
+--------------+---------------------+-------------+---------------+
| 222005001 | 2019-05-10 10:01:01 | Alvaro | Garcia |
| 222004001 | 2019-05-13 16:14:21 | David | Garcia |
| 111003001 | 2019-05-13 16:14:43 | Roberto | Martin |
| 111001000 | 2019-05-13 16:14:50 | Juan Manuel | Martin |
| 111001000 | 2019-05-13 16:14:50 | Maria | Alonso |
| 111001000 | 2019-05-13 16:14:50 | Roberto | Martin |
| 333006001 | 2019-05-13 16:14:55 | Benito | Lopera |
| 123456789 | 2019-05-13 16:15:00 | NULL | NULL |
| 987654321 | 2019-05-13 16:15:08 | NULL | NULL |
| 123456789 | 2019-05-13 16:15:13 | NULL | NULL |
| 666999666 | 2019-05-13 16:15:18 | NULL | NULL |
| 454545458 | 2019-05-13 16:15:27 | NULL | NULL |
| 333006001 | 2019-05-13 16:23:36 | Benito | Lopera |
| 987654321 | 2019-05-13 16:23:46 | NULL | NULL |
| 666999666 | 2019-05-13 16:23:50 | NULL | NULL |
| 454545458 | 2019-05-13 16:23:55 | NULL | NULL |
| 666999666 | 2019-05-13 16:24:03 | NULL | NULL |
| 222004001 | 2019-05-13 16:24:10 | David | Garcia |
+--------------+---------------------+-------------+---------------+
Sort them like this:
+--------------+---------------------+-------------+---------------+
| phone_number | registered | name | first_surname |
+--------------+---------------------+-------------+---------------+
| 222004001 | 2019-05-13 16:24:10 | David | Garcia |
| 222004001 | 2019-05-13 16:14:21 | David | Garcia |
| 666999666 | 2019-05-13 16:24:03 | NULL | NULL |
| 666999666 | 2019-05-13 16:23:50 | NULL | NULL |
| 666999666 | 2019-05-13 16:15:18 | NULL | NULL |
| 454545458 | 2019-05-13 16:23:55 | NULL | NULL |
| 454545458 | 2019-05-13 16:15:27 | NULL | NULL |
| 987654321 | 2019-05-13 16:23:46 | NULL | NULL |
| 987654321 | 2019-05-13 16:15:08 | NULL | NULL |
| 333006001 | 2019-05-13 16:23:36 | Benito | Lopera |
| 333006001 | 2019-05-13 16:14:55 | Benito | Lopera |
| 123456789 | 2019-05-13 16:15:13 | NULL | NULL |
| 123456789 | 2019-05-13 16:15:00 | NULL | NULL |
| 111001000 | 2019-05-13 16:14:50 | Maria | Alonso |
| 111001000 | 2019-05-13 16:14:50 | Roberto | Martin |
| 111001000 | 2019-05-13 16:14:50 | Juan Manuel | Martin |
| 111003001 | 2019-05-13 16:14:43 | Roberto | Martin |
| 222005001 | 2019-05-10 10:01:01 | Alvaro | Garcia |
+--------------+---------------------+-------------+---------------+
It can be done with this query:
SELECT c.phone_number, c.registered, cl.name, cl.first_surname
FROM callers cl
INNER JOIN callers_phones cp ON cl.caller_id = cp.caller_id
RIGHT OUTER JOIN calls c ON c.phone_number = cp.phone_number
JOIN (
SELECT phone_number, MAX(registered) AS registered
FROM calls
GROUP BY phone_number) aux_c ON aux_c.phone_number = c.phone_number
WHERE c.answered = FALSE
AND (null is null or null is null or c.registered between null and null)
AND (null is null or c.phone_number = null)
AND (null is null or cl.caller_id = null)
ORDER BY aux_c.registered DESC, c.registered DESC
These are the tables:
CREATE TABLE callers
(
caller_id int NOT NULL UNIQUE AUTO_INCREMENT,
name varchar(50) NOT NULL,
first_surname varchar(50) NOT NULL,
CONSTRAINT callers_pkey PRIMARY KEY (caller_id)
);
CREATE TABLE callers_phones
(
phone_id int NOT NULL UNIQUE AUTO_INCREMENT,
caller_id int NOT NULL,
phone_number int NOT NULL,
CONSTRAINT callers_phones_pkey PRIMARY KEY (phone_id)
);
ALTER TABLE callers_phones
ADD CONSTRAINT callers_phones_fkey_callers FOREIGN KEY (caller_id)
REFERENCES callers (caller_id);
CREATE TABLE calls
(
call_id int NOT NULL UNIQUE AUTO_INCREMENT,
phone_number int NOT NULL,
answered boolean NOT NULL DEFAULT false,
registered datetime NOT NULL,
CONSTRAINT calls_pkey PRIMARY KEY (call_id)
);
The problem is that we have to implement it in JPA with paging, but subqueries do not work in JOIN clause, and paging does not work with nativeQuery.
This is what we have done:
#Entity:
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.EntityResult;
import javax.persistence.FieldResult;
import javax.persistence.Id;
import javax.persistence.NamedNativeQuery;
import javax.persistence.SqlResultSetMapping;
#SqlResultSetMapping (name = "MissedCallResult",
entities = {
#EntityResult (entityClass = MissedCallEntity.class,
fields = {
#FieldResult (name = "callId", column = "id"),
#FieldResult (name = "phoneNumber", column = "pH"),
#FieldResult (name = "registered", column = "reg"),
#FieldResult (name = "callerName", column = "cN"),
#FieldResult (name = "callerFirstSurname", column = "cFS")
})
})
#NamedNativeQuery (name = "findMissedCalls",
query = "select c.call_id as id, c.phone_number as pH, c.registered as reg, cl.name as cN, cl.first_surname as cFS "
+ "from callers cl "
+ " inner join callers_phones cp on cl.caller_id = cp.caller_id "
+ " right outer join calls c on c.phone_number = cp.phone_number "
+ " join (select c2.phone_number, MAX(c2.registered) as registered "
+ " from calls c2 "
+ " group by c2.phone_number) aux_c on aux_c.phone_number = c.phone_number "
+ "where c.answered = false "
+ " and (:startDate is null or :endDate is null or c.registered between :startDate and :endDate) "
+ " and (:callerId is null or cl.caller_id = :callerId) "
+ " and (:phoneNumber is null or c.phone_number = :phoneNumber) "
+ "order by aux_c.registered desc, c.registered desc",
resultSetMapping = "MissedCallResult")
#Entity
public class MissedCallEntity
{
#Id
private Integer callId;
private Integer phoneNumber;
private Date registered;
private String callerName;
private String callerFirstSurname;
private String callerSecondSurname;
...
}
#Repository:
import java.util.Date;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import es.panel.domain.MissedCallEntity;
#RepositoryRestResource (path = "missedCalls", collectionResourceRel = "missedCalls")
public interface MissedCallRepository extends PagingAndSortingRepository<MissedCallEntity, Integer>
{
#Query (nativeQuery = true, name = "findMissedCalls")
Page<MissedCallEntity> findMissedCalls(#Param ("startDate") Date startDate,
#Param ("endDate") Date endDate,
#Param ("callerId") Integer callerId,
#Param ("phoneNumber") Integer phoneNumber,
Pageable page);
}
In #Service:
public Page<MissedCallEntity> getMissedCalls(Date startDate,
Date endDate,
Integer callerId,
Integer phoneNumber,
int actualPage,
int limit)
{
Page<MissedCallEntity> calls = mcRepository.findMissedCalls(
startDate, endDate, callerId, phoneNumber, PageRequest.of(1, 5));
return calls;
}
Thanks in advance!
A very simple solution is to create a database view based on your query for the calculated values i.e. counts and max values etc.
You can map this to the relevant entity using the JPA #SecondaryTable annotation which lets you map an entity to more than 1 table (or view).
With this is place you can the sort and filter using standard JPA/spring data functionality just as for any other field and you can pretty much remove all the code you have written.
I would elaborate further however it is not very clear what you are trying to achieve: you are asking about your attempted solution rather than the problem itself. Neither is MissedCall an entity. The entities in your system are users, calls, phones etc.
I have the following result set, that I'm trying to drill down
+----+---------+---------------+---------------------+----------------------+---------------+-----------+------------------+------------------+
| id | auth_id | trusts_number | buy_sell_actions_id | corporate_actions_id | fx_actions_id | submitted | created_at | updated_at |
+----+---------+---------------+---------------------+----------------------+---------------+-----------+------------------+------------------+
| 2 | 6 | N100723 | 2 | NULL | NULL | 0 | 08/05/2015 11:30 | 08/05/2015 15:32 |
| 5 | 6 | N100723 | NULL | NULL | 1 | 0 | 08/05/2015 15:10 | 08/05/2015 15:10 |
| 6 | 6 | N100723 | NULL | NULL | 2 | 1 | 08/05/2015 15:12 | 08/05/2015 15:41 |
+----+---------+---------------+---------------------+----------------------+---------------+-----------+------------------+------------------+
This result set is generated with the query
SELECT * FROM actions WHERE auth_id = 6 AND trusts_number = 'N100723'
I also want to get rid of any field with fx_actions is NULL, so I change the query to
SELECT * FROM actions WHERE auth_id = 6 AND trusts_number = 'N100723' AND fx_actions_id != NULL
However this returns an empty result set. I've never used "negative" query parameters in MySQL before, so I'm not sure if they should take on a different syntax or what?
Any help would be much appreciated.
Normal comparison operators don't work well with NULL. Both Something = NULL and Something != NULL will return 'unknown', which causes the row to be omitted in the result. Use the special operators IS NULL and IS NOT NULL instead:
SELECT * FROM actions
WHERE auth_id = 6
AND trusts_number = 'N100723'
AND fx_actions_id IS NOT NULL
Wikipedia on NULL and its background
Because null isn't a value, you should use IS NOT NULL
Currently I am trying to parse large xml file, Here is the how my xml file looks like:
<post>
<row Id="22" PostTypeId="2" ParentId="9" CreationDate="2008-08-01T12:07:19.500" Score="7" Body="<p>The best way that I know of because of leap years and everything is:</p>
<pre><code>DateTime birthDate = new DateTime(2000,3,1);<br>int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);<br></code></pre>
<p>Hope this helps.</p>" OwnerUserId="17" LastEditorUserId="17" LastEditorDisplayName="Nick" LastEditDate="2008-08-01T15:26:37.087" LastActivityDate="2008-08-01T15:26:37.087" CommentCount="1" CommunityOwnedDate="2011-08-16T19:40:43.080" />
<row Id="29" PostTypeId="2" ParentId="13" CreationDate="2008-08-01T12:19:17.417" Score="18" Body="<p>There are no HTTP headers that will report the clients timezone so far although it has been suggested to include it in the HTTP specification.</p>
<p>If it was me, I would probably try to fetch the timezone using clientside JavaScript and then submit it to the server using Ajax or something.</p>" OwnerUserId="19" LastActivityDate="2008-08-01T12:19:17.417" CommentCount="0" />
</post>
Different between these two records in this XML file is that doesn't have LastEditDate element. I believe as a result of that I get the following error:
/ruby/1.9.2/ubuntuamd1/lib/ruby/1.9.1/date/format.rb:1031:in `dup': can't dup NilClass (TypeError)
from /soft/ruby/1.9.2/ubuntuamd1/lib/ruby/1.9.1/date/format.rb:1031:in `_parse'
from /soft/ruby/1.9.2/ubuntuamd1/lib/ruby/1.9.1/date.rb:1732:in `parse'
from load.rb:105:in `on_start_element'
from load.rb:165:in `parse'
Here is the code segment that its getting referred:
if element == 'row'
#post_st.execute(attributes['Id'], attributes['PostTypeId'], attributes['AcceptedAnswerId'], attributes['ParentId'], attributes['Score'], attributes['ViewCount'],
attributes['Body'], attributes['OwnerUserId'] == nil ? -1 : attributes['OwnerUserId'], attributes['LastEditorUserId'], attributes['LastEditorDisplayName'],
DateTime.parse(attributes['LastEditDate']).to_time.strftime("%F %T"), DateTime.parse(attributes['LastActivityDate']).to_time.strftime("%F %T"), attributes['Title'] == nil ? '' : attributes['Title'],
attributes['AnswerCount'] == nil ? 0 : attributes['AnswerCount'], attributes['CommentCount'] == nil ? 0 : attributes['CommentCount'],
attributes['FavoriteCount'] == nil ? 0 : attributes['FavoriteCount'], DateTime.parse(attributes['CreationDate']).to_time.strftime("%F %T"))
post_id = attributes['Id']
furthermore I think this is the line where I look for LastEditDate
DateTime.parse(attributes['LastEditDate']).to_time.strftime("%F %T"), DateTime.parse(attributes['LastActivityDate']).to_time.strftime("%F %T"), attributes['Title'] == nil ? '' : attributes['Title']
I guess since the element doesn't exist I get the above mentioned error. I was wondering how do I handle this scenario where if an element doesn't exist set it to a default value. Because while I am parsing these record I insert them into MySQL database. Which has following table structure:
+--------------------------+--------------+------+-----+---------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------------+--------------+------+-----+---------------------+-----------------------------+
| id | int(11) | NO | PRI | NULL | |
| post_type_id | int(11) | NO | | NULL | |
| accepted_answer_id | int(11) | YES | | NULL | |
| parent_id | int(11) | YES | MUL | NULL | |
| score | int(11) | YES | | NULL | |
| view_count | int(11) | YES | | NULL | |
| body_text | text | YES | | NULL | |
| owner_id | int(11) | NO | | NULL | |
| last_editor_user_id | int(11) | YES | | NULL | |
| last_editor_display_name | varchar(40) | YES | | NULL | |
| last_edit_date | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
| last_activity_date | timestamp | NO | | 0000-00-00 00:00:00 | |
| title | varchar(256) | NO | | NULL | |
| answer_count | int(11) | NO | | NULL | |
| comment_count | int(11) | NO | | NULL | |
| favorite_count | int(11) | NO | | NULL | |
| created | timestamp | NO | | 0000-00-00 00:00:00 | |
+--------------------------+--------------+------+-----+---------------------+-----------------------------+
I have setup last_edit_date as not null column.
Based on the answer provided I made the change but error still remains the same:
def convert_to_mysql_time(date='1973-01-01T01:01:01.000')
DateTime.parse(date).to_time.strftime("%F %T")
end
def on_start_element(element, attributes)
if element == 'row'
#post_st.execute(attributes['Id'], attributes['PostTypeId'], attributes['AcceptedAnswerId'], attributes['ParentId'], attributes['Score'], attributes['ViewCount'],
attributes['Body'], attributes['OwnerUserId'] == nil ? -1 : attributes['OwnerUserId'], attributes['LastEditorUserId'], attributes['LastEditorDisplayName'],
convert_to_mysql_time(attributes['LastEditDate']), DateTime.parse(attributes['LastActivityDate']).to_time.strftime("%F %T"), attributes['Title'] == nil ? '' : attributes['Title'],
attributes['AnswerCount'] == nil ? 0 : attributes['AnswerCount'], attributes['CommentCount'] == nil ? 0 : attributes['CommentCount'],
attributes['FavoriteCount'] == nil ? 0 : attributes['FavoriteCount'], DateTime.parse(attributes['CreationDate']).to_time.strftime("%F %T"))
post_id = attributes['Id']
Here is the error:
/ruby/1.9.2/ubuntuamd1/lib/ruby/1.9.1/date/format.rb:1031:in `dup': can't dup NilClass (TypeError)
from /soft/ruby/1.9.2/ubuntuamd1/lib/ruby/1.9.1/date/format.rb:1031:in `_parse'
from /soft/ruby/1.9.2/ubuntuamd1/lib/ruby/1.9.1/date.rb:1732:in `parse'
from load.rb:102:in `convert_to_mysql_time'
from load.rb:109:in `on_start_element'
from load.rb:169:in `parse'
from load.rb:169:in `<main>'
I would, write a method that converts String dates to MySQL dates, and supply it a default value if the nil is supplied to the method, e.g:
def convert_to_my_sql_date(date)
date = '1973-01-01T01:01:01.000' if (date.empty? rescue true) #was added since empty string gets supplied as an argument, and the rescue to make arguments that do not respond to empty? take a default date
DateTime.parse(date).to_time.strftime("%F %T")
end
So when the date is nil it uses the default, then you can now use as below in your method:
convert_to_my_sql_date(attributes['LastEditDate'])
I'm getting some weird results when I query on of my tables to show upcoming birthdays (schema and query below), and then sort by date with the upcoming dates first. The type for the dob (date of birth) field is date with the format 0000-00-00
I'm using the below schema:
People:
+------------+-------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+-------------------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| fname | varchar(32) | NO | | NULL | |
| lname | varchar(32) | NO | | NULL | |
| dob | date | NO | | 0000-00-00 | |
| license_no | varchar(24) | NO | | NULL | |
| date_added | timestamp | NO | | CURRENT_TIMESTAMP | |
| status | varchar(8) | NO | | Allow | |
+------------+-------------+------+-----+-------------------+----------------+
and here's my query, as it's called from PHP:
<?php
/* This will give us upcoming dobs for the next 2 weeks */
$con = connect_db();
// grab any dobs coming up in the next week and sort them by what's
//coming up first
//if they are born on Feb. 29th, it will fall on March 1st
$query = 'select p.lname, p.fname, u.number, p.dob ' .
'from people p, units u where p.id = u.resident and ' .
'DAYOFYEAR(curdate()) <= DAYOFYEAR(DATE_ADD(dob, INTERVAL ' .
'(YEAR(NOW()) - YEAR(dob)) YEAR)) AND DAYOFYEAR(curdate()) +30 >= ' .
'dayofyear(`dob`) order by dayofyear(dob) limit 7;';
$result = mysqli_query($con, $query);
if (!empty($result)) {
while($row = mysqli_fetch_array($result)) {
$fname = $row['fname'];
$lname = $row['lname'];
$number = $row['number'];
$dob = date("m-d", strtotime($row['dob']));
if($dob == date("m-d")) {
$dob = 'Today!';
printf('%s, %s</br>Unit: %s</br>%s</br></br>', $lname,
$fname, $number, $dob);
} else {
printf('%s, %s</br>Unit: %s</br>Date: %s</br></br>', $lname,
$fname, $number, $dob);
}
}
}
?>
here's an example of the returned query:
Name, Name
Unit: 110
Date: 09-11
Name2, Name2
Unit: 434
Date: 09-10
As you can see, the order is wrong!
EDIT - Now I've noticed that the records in question (the two dates above) are not ordered correctly ever in MySQL!
One of the full dates is: 1950-09-11
and the other is: 1956-09-10
I've looked through those two records and haven't found any mangled data, so I'm pretty confused as to why this is happening
ORDER BY dayofyear(dob) ASC
Good luck