Как суммировать поле двух разных таблиц с другим полем, используя между датой и групповой даты в Android SQLite - PullRequest
0 голосов
/ 04 ноября 2019
    public List<BillModel> Daily_Sales_Report(String from) {// passing the 

дата получения данных, дата указана из таблицы List list = new ArrayList ();Строковый запрос = "выберите сумму (Discount), сумму (Del_ch), сумму (Pkg_ch), substr (Created_Date, 0,11) из BILLING, где substr (Created_Date, 0,11) как группа" + from + "" по substr (Created_Date, 0, 11) ";Строка query1 = "select count (*), sum (Amount), sum (gst_price), Created_Date из корзины, где Created_Date похож на группу" + from + "по Created_Date";

//here i used to cursor for getting the result from two different table and setting in the model class setter.
                Cursor cursor = this.getWritableDatabase().rawQuery(query, null);
                Cursor cursor1= this.getWritableDatabase().rawQuery(query1,null);
               if (cursor.moveToFirst()&& cursor1.moveToFirst()){// cursor and cursor1 will check the data from first positon 
                    String bill_date= cursor1.getString(3  ); //getting the date from table bill
                    String cart_date= cursor.getString(  3);//getting the cart_date from cart_table
                    try {
                        do {
                            if (bill_date==cart_date){ //if cart_date from cart_table ,and bill_date from bill_table will match then it will set in the setter other wise condition will check countiue in while loop                                   BillModel model = new BillModel(); //model class
                                 model.setbill_count( cursor1.getInt( 0 ) );   // here its for count total number of item
                                model.setC_Amount( cursor1.getFloat( 1 ) );
                                model.setB_total_gst( cursor1.getFloat( 2 ) );
                                model.setB_discount( cursor.getFloat( 0 ) );
                                model.setB_del_ch( cursor.getInt( 1 ) );
                                model.setB_pack_ch( cursor.getInt( 2 ) );
                                model.setB_create_date( cursor.getString( 3) );
                               list.add( model );
                            }
                       } while (cursor.moveToNext()&& cursor1.moveToNext());// using while loop for both the cursor
                    } catch (Exception e) {
                        Log.e( "Error", String.valueOf( e ) );
                    } finally {
                        cursor.close();
                        cursor1.close();
                    }
                }
                return list;
            }

i am trying to this,What's I am doing wrong here,not getting the result in model class variable. Is it write way or not?

Ответы [ 2 ]

0 голосов
/ 05 ноября 2019

В результате вы получите правильный ответ на запрос, который вы написали. Результатом является эффект левого соединения.

Пример

Результирующая таблица 'левого соединения' без 'group by' будет

select * 
from CART left join BILLING on CART.index=BILLING.index 
where substr(BILLING.Created_Date,0,11) = '02/11/2019'

enter image description here

Здесь в «CART» две строки с индексом = 1, а в «BILLING» только одна строка с индексом = 1. Поэтому, когда используется «левое соединение», строка фактуры появится дважды. Поэтому, когда вы используете 'group by', эти значения суммируются.

0 голосов
/ 04 ноября 2019

Существует проблема с тем, как вы сохраняете даты. Согласно SQLite, ваше поле «Created_Date» является строкой.

SQLite сравнивает строки буква за буквой

Пример:

Согласно SQLite на 01/11/2019 меньше 21/ 10/2019, поскольку первая дата начинается с ' 0 ', а вторая дата начинается с ' 2 '.


Чтобы устранить эту проблему,можно использовать различные форматы даты, такие как

  • гггг / мм / дд : 2019/11/01
  • гггг / мм / дд ЧЧ: мм:сс : 2019/11/01 14: 21: 43
...