Добрый,

Информации мало. Но если коротко то вам для кнопки с запросом нужно привести свой запрос к такому виду
(я напишу очень упрощенно):

SELECT Клиент, MAX(Дата)  FROM Таблица WHERE Ваши условия GROUP BY Клиент;

GROUP BY - Выведет уникального клиента т.е. 1 раз
MAX(Дата) - Выведет для этого 1 раза максимальную дату

777

(2 replies, posted in General)

if you use Report SQL or Button action SQL query use

{edit5}

where jobs.id = {edit5}

http://myvisualdatabase.com/help_en/SQLquery.html


in script sql query
use '+jobsfiles.edit5.sqlValue+'  or  '''+jobsfiles.edit5.text+'''

http://myvisualdatabase.com/help_en/script_edit.html

778

(14 replies, posted in Russian)

Если у вас "Время на дистанции", "Штраф за пропуск" определено в программе как  ДатаВремя или Время, а "ПропускКП" как целое то никаких дополнительных преобразований Time() не требуется. Просто используйте мой пример но подставьте свои поля данных из таблицы.

779

(14 replies, posted in Russian)

tserduk wrote:

Я так делал, не получается, пишет "invalid действия с плавающей точкой". Не хочет умножать время на число.
Вот это выражение не работает -- strftime('%s',time(TimeTaxO)*(taxO))


Я прошу прощения, но где у меня в примере такая строчка как у вас ?

TIME((STRFTIME('%s', Время на дистанции) + STRFTIME('%s', Штраф за пропуск) * Пропуск КП), 'unixepoch')

Прежде чем дать вам я проверил работает ли это.

Вот проверка

TIME((STRFTIME('%s', '00:45:00') + STRFTIME('%s', '00:20:00') * 2), 'unixepoch')
01:25:00

780

(14 replies, posted in Russian)

В базе данных вам достаточно хранить информацию Время на дистанции, Пропуск КП, Штраф за пропуск(20 мин).
Соответственно в программе должны быть поля для ввода этих данных. .
Вычисления для поля Результат можно производить в вычисляемом поле для вывода в таблице на экран или в репорт.


Вот что должно быть в вычисляемом поле:


Время на дистанции + (Пропуск * Штраф за пропуск)

TIME((STRFTIME('%s', Время на дистанции) + STRFTIME('%s', Штраф за пропуск) * Пропуск КП), 'unixepoch')

Только руками

782

(14 replies, posted in Russian)

Умножить и поместить это не проблема.
Необязательно записывать вычисленное значение.Значение можно вычислить моментально в любом запросе и подставить для решения дальше. Все зависит от объема базы даных ее структуры и выводимой информации.

Но для того чтоб дать вам совет нужно понять вашу задачу или увидеть пример.
Вам нужно понимать какая у вас база данных, какой структуры, как данные будут вводиться в программе,
что вы хотите видеть в программе и какие выходные данные в каком виде?
А скрипт дело наживное.
Начните с малого. Здесь в форуме много примеров любой сложности.

Если у вас до этого небыло опыта работы с базами данных можно прочитать здесь
http://myvisualdatabase.com/forum/misc. … download=1
Советую обратить внимание на тему k245
http://myvisualdatabase.com/forum/viewtopic.php?id=4593

It is possible in this way for a table column. Then there is no need for a calculated field

TNxNumberColumn(Form1.TableGrid1.Columns[i]).FormatMask := 'hh:nn am/pm';
TNxNumberColumn(Form1.TableGrid1.Columns[0]).FormatMask := 'dd mmmm YYYY';

785

(14 replies, posted in Russian)

tserduk wrote:

Ввожу:

TIME((STRFTIME('%s',time(Mtime))*2 , 'unixepoch')

Пишет:

near ",": syntax error

В чем проблема?

а что вы хотите сделать ?
Просто умножить Mtime * 2 ?

Тогда

SELECT TIME((STRFTIME('%s', Mtime))*2, 'unixepoch')

Check out an example. The REPORT uses only the eDateTime field. Shows month and time as am / pm.
yellow and green fields show different methods
in the table of form1 the 'time am / pm' field is displayed

787

(14 replies, posted in Russian)

Все будет корректно до 23:59:59. 24 часа отобразится снова как  00:00:00.
Обработка в формате более 24 часов потребует изменить решение


Для SQLite

00:20:00 * 5


1.пересчитать время в секунды
  00:20:00 = 1200
2.умножить на 5
  1200 * 5 = 6000
3. в sqlite используем функцию time()
  time(6000, 'unixepoch') = 01:40:00


01:45:00 * 2
6300 * 2
time(12600, 'unixepoch') = 03:30:00

SELECT TIME((STRFTIME('%s', '01:45:00'))*2, 'unixepoch')

Для скрипта:

Form1.Edit1.Text := TimeToStr(StrToTime('01:45:00')*2);
= 03:30:00

http://myvisualdatabase.com/forum/viewtopic.php?id=1056

Hi,

in the program you can use the advice brian.zaballa but for REPORT :


1. red field "(the red date on the report)" in REPORT write new text

[StrToDateTime(<Report."event.eDateTime">)]

2. in format tab select Date\Time and "format string" type mmmm (or what do yo want... for example hh:mm am/pm wink )
the same as
  DisplayFormat
    FormatStr: mmmm
    Kind: fkDateTime


OR


1. red field "(the red date on the report)" in REPORT write new text (month or time with am/pm)

[FormatDateTime('mmmm',StrToDateTime(<Report."event.eDateTime">))] 
or
[FormatDateTime('hh:nn:ss am/pm',StrToDateTime(<Report."event.eDateTime">))]
or
[StrToDateTime(<Report."event.eDateTime">) #dmmmm]
or
[StrToDateTime(<Report."event.eDateTime">) #dhh:mm am/pm]

2. in format tab select Text (no formatting).
the same as
  DisplayFormat
    FormatStr:
    Kind: fkText


Thats all

The date and time is displayed in the table and in the program depending on the regional settings in WINDOWS. But if you really need it, you can create a calculated field with something like this(adapted from the internet ). And output it to a table.

CASE WHEN strftime('%H', eDateTime) % 12 = 0 
        THEN 12 
        ELSE strftime('%H', eDateTime) % 12 END 
        || ':' || strftime('%M', eDateTime)
    || ' ' ||
    CASE WHEN
        strftime('%H', eDateTime)-0 >= 12 THEN 'PM'
        ELSE 'AM' END 

You can create event frmMain_dtpFilter_OnChange
and write to script

procedure frmMain_dtpFilter_OnChange (Sender: TObject);
begin
  frmMain.TableGrid1.dbFilter := 'event.eDate >= '+frmMain.dtpFilter.sqlDate+' AND event.eDate < strftime(''%Y-%m'','+frmMain.dtpFilter.sqlDate+',''+1 month'')';
  frmMain.TableGrid1.dbUpdate;
end;

Remove the name btnSearch from dtpFilter(Increm.Search) and the search button itself.


OR


you can do it via SQL query on the button.
Write your query and process one DateTimePicker.

SELECT event.name, event.eDate, event.id
FROM event
WHERE event.eDate >= {dtpFilter} 
AND event.eDate < strftime('%Y-%m',{dtpFilter},'+1 month')

The disadvantage of this approach is writing your own query and processing the table when changing (event OnChange)

791

(5 replies, posted in Reports)

joshuA wrote:

I answered another user here (perhaps too late) that was asking how to do that very thing.

Hi, smile

Yes, your approach is correct. But there is a difference between your case and this one. In your case, this is not enough, since the SUM will not work.
Create event in TextObject OnBeforePrint
For your case in the script

var
 leg_M: integer;    

procedure ReportbLegcfLegMileageOnBeforePrint(Sender: TfrxComponent);                       
begin           
  if not ValidInt(<Report."bLeg.cfLegMileage">) then                                   
    leg_M := 0 else leg_M := StrToInt(<Report."bLeg.cfLegMileage">);                                
end;

begin

end.

in MasterData for TextObject instead of [Report."bLeg.cfLegMileage"] write your variable [<leg_M>].
in GroupFooter1 for TextObject instead of [SUM(<Report."bLeg.cfLegMileage">,MasterData1)] write [SUM(<leg_M>,MasterData1)].
in GroupFooter2 for TextObject instead of [SUM(<Report."bLeg.cfLegMileage">,MasterData1)] write [SUM(<leg_M>,MasterData1)].


Lets you revert to a numeric representation (integer in this case)
It is easier to write IFNULL in the request.

That's all


P.S. For 7410_project and your project.
       If you do not want to display 0. You can enable in TextObject properties - HideZeros: True and the field remains blank.

792

(5 replies, posted in Reports)

Possible solution via FastReport script.
The solution is to replace NULL with '0'.
Slightly more complicated than I suggested above.

793

(5 replies, posted in Reports)

Hi
These NULLs cause this result

name          OD         start     finish      diff
Kelon Decee    637381    637381    NULL    NULL
Kelon Decee    637500    637500    637381    119
Kelon Decee    637782    637782    637500    282
Noren Boley    635729    635729    NULL    NULL
Noren Boley    635917    635917    635729    188
Noren Boley    636129    636129    635917    212

please modify CALCULATED FIELD  cfLegMileage

IFNULL((select max(x.od) from bleg x where x.od = bleg.od and x.id_atrip = atrip.id)  
-
(select max(x.od) from bleg x where x.od < bleg.od and x.id_atrip = atrip.id),0) 

and simplify , works faster

IFNULL((SELECT bLeg.OD - max(b.OD) FROM bLeg b WHERE bLeg.id_aTrip = b.id_aTrip and b.OD  < bLeg.OD),0)

AFTER

name            OD        start    finish    diff res
Kelon Decee    637381    637381    NULL    0
Kelon Decee    637500    637500    637381    119
Kelon Decee    637782    637782    637500    282
Noren Boley    635729    635729    NULL    0
Noren Boley    635917    635917    635729    188
Noren Boley    636129    636129    635917    212

You need to be careful when you create your databases and queries to it.

If you create related columns in your tables, then do not forget to fill them in these tables.
If you refer to a table in a query and mention a related column in another table,
do not forget about the JOIN (INNER or LEFT) of the other table ON related column.
If you have created a column, think about whether to put a default value (zero or something else).
I drew your attention to these things in the previous topic.


Yes, your project has gone relatively far, but you need to strive to simplify and optimize databases, tables, queries.


To test the correctness of your program, create yourself a database with the most correct data.
Otherwise, you will end up running in circles between your code and the database.


Strive for your program to fill in all the necessary data in the tables and then work with the output forms.
Create a form for yourself with one table and display the data of the tables in it one by one to control the correctness of filling.
To work with the database, you can use SQLlite administration programs.


Everything else works correctly in an MVD program (almost smile).


Sorry. Translate by Google.

794

(2 replies, posted in General)

Please look here

http://myvisualdatabase.com/forum/viewtopic.php?id=4287

795

(6 replies, posted in General)

Yes, you need to use JOIN.

A JOIN clause is used to combine rows from two or more tables, based on a related column between them

The simplest JOIN example:

SELECT EquipName, EqModel, EqPurchDate,
       EqNotes, EqSparePart, EquipType
             
FROM tbl_Equip, tbl_EquipType

WHERE tbl_Equip.RELATED COLUMN = tbl_EquipType.RELATED COLUMN

AND tbl_Equip.EqSparePart LIKE "Installed" 

RELATED COLUMN - replace with your related column.

you can read about JOIN on the Internet.

796

(6 replies, posted in General)

Создав событие OnShow для главной формы, примените функцию SetWindowLong для каждой формы, кроме главной, пример:

After creating an OnShow event for the main form, apply the SetWindowLong function for each form except the main one, example:
http://myvisualdatabase.com/forum/viewtopic.php?id=4025

procedure Form1_OnShow (Sender: TObject; Action: string);
begin
    SetWindowLong(Form2.Handle, GWL_EXSTYLE, GetWindowLong(Form2.Handle, GWL_EXSTYLE) xor WS_EX_APPWINDOW);
    SetWindowLong(Form3.Handle, GWL_EXSTYLE, GetWindowLong(Form3.Handle, GWL_EXSTYLE) xor WS_EX_APPWINDOW);
end;

During my attempt to rewrite the request, I got an unexpected result. After analysis, I can say: Your troubles are the result of a not very good database structure
and the TRIP and TRIPLEG tables do not match in the STATE (id_state) part. There may be other errors.
In the future, you may face unpredictable calculations.
Create the tables in the correct state with your data.

in some cases, values are passed as text. Calculation and display errors occur.
Try to use :

SUM(CASE WHEN tl.fuelGallons > 0 then tl.fuelGallons else '0,0' end) as "TotalGallons"

or

SUM(IFNULL(tl.fuelGallons,'0,0')) as "TotalGallons"

799

(6 replies, posted in General)

CheckBox component properties:


AllowGrayed -  Determines whether check box can be in a "grayed" state.
http://myvisualdatabase.com/help_en/CheckBox.html - please read.


Put "AllowGrayed" in the FALSE state and you will have only YES and NO.

800

(9 replies, posted in Russian)

Посмотрите еще этот момент у себя

     // если пользователь обладает правами администратора,
          if s='1' then
          frmUsers.Show;
          frmUsers.TableGrid1.dbUpdate;                  
          frmUsers.TableGrid2.dbUpdate;         
          frmUsers.TableGrid3.dbUpdate;

     // если пользователь не обладает правами администратора,          
          if s='0' then
          Letters.Show;
          Letters.TableGrid1.dbUpdate;

После проверки условия if s= ...
выполняется только ....Show;
dbUpdate для форм выполняется подряд.

Возможно так ?

     // если пользователь обладает правами администратора,
          if s='1' then
          begin
            frmUsers.Show;
            frmUsers.TableGrid1.dbUpdate;                  
            frmUsers.TableGrid2.dbUpdate;         
            frmUsers.TableGrid3.dbUpdate;
          end;

     // если пользователь не обладает правами администратора,          
          if s='0' then
          begin
            Letters.Show;
            Letters.TableGrid1.dbUpdate;
          end;