SQLlite strftime function to get grouped data by months - sql

i have table with following structure and data:
I would like to get grouped data by months in given date range for example (from 2014-01-01 to 2014-12-31). Data for some months cannot be available but i still need to have in result information that in given month is result 0.
Result should have following format:
MONTH | DIALS_CNT | APPT_CNT | CONVERS_CNT | CANNOT_REACH_CNT |
2014-01 | 100 | 50 | 20 | 30 |
2014-02 | 100 | 40 | 30 | 30 |
2014-03 | 0 | 0 | 0 | 0 |
etc..
WHERE
APPT_CNT = WHERE call.result = APPT
CONVERS_CNT = WHERE call.result = CONV_NO_APPT
CANNOT_REACH_CNT = WHERE call.result = CANNOT_REACH
How can i do it please with usage function strftime ?
Many thanks for any help or example.

SELECT Month,
(SELECT COUNT(*)
FROM MyTable
WHERE date LIKE Month || '%'
) AS Dials_Cnt,
(SELECT SUM(Call_Result = 'APPT')
FROM MyTable
WHERE date LIKE Month || '%'
) AS Appt_Cnt,
...
FROM (SELECT '2014-01' AS Month UNION ALL
SELECT '2014-02' UNION ALL
SELECT '2014-03' UNION ALL
...
SELECT '2014-12')

Related

How to limit a SUM using postgres

I want to limit the SUM to 2 hours in postgres sql. I dont want to limit the result of the sum, but the value that it is going to sum.
For example, the following table:
In this case, if I SUM('02:20', '01:50', '00:30', '03:00') the result would be 07:30.
|CODE | HOUR |
| --- | ---- |
| 1 | 02:20 |
| 2 | 01:50 |
| 3 | 00:30 |
| 4 | 03:00 |
But what i want, is to limit the column HOUR to 02:00. So if the value is > 02:00, it will be replaced with 02:00, only in the SUM.
So the SUM should look like this ('02:00', '01:50', '00:30', '02:00'), and the result would be 06:20
Use case as an argument of the function:
select sum(case when hour < '2:00' then hour else '2:00' end)
from my_table
Test it in Db<>fiddle.
It's still not perfect, but the idea is this:
select sum(x.anything::time)
from (select id,
time,
case when time <= '02:00' then time::text
else '02:' || (EXTRACT(MINUTES FROM time::time)::text)
end as anything
from time_table) x

SQL: Selecting data from multiple tables with multiple records to select and join

I have three tables: VolunteerRelationships, Organizations, and CampaignDates. I'm trying to write a query that will give me the organization id and name, and the org's start and end campaign dates for the current campaign year <#CampaignYear>, based on the selected volunteer <#SelectedInd>.
Dates are stored as separate column values for day, month and year which I'm trying to cast into a more an formatted date value. If I can get this, I'd also like to use a case statement to get the status of the campaign based on whether the date campaign dates are upcoming, currently running, or already closed, but need to get the first part of the query first.
Sorry if I'm leaving a lot of needed info out, this is my first time posting a question to this forumn. Thank you!
VolunteerRelationships
id | name | managesId |expiryDate
1 | john | 1 |
2 | jack | 2 |6/30/2020
3 | jerry| 3 |12/31/2021
Organizations
id | name1
1 | ACME
CampaignDates
orgId | dateDay | dateMonth | dateYear | dateType | Campaign Year
1 | 5 | 11 | 2020 | Start | 2020
1 | 15 | 11 | 2020 | End | 2020
Result
orgId | orgName | startDate | endDate | Status
1 | ACME | 2020-01-01| 2020-01-15 | Closed
select
v.MANAGEDACCOUNT,
o.Name1,
select * from
(select cast(cast dateyear*1000 + datemonth*100 + dateday as varchar(255)) as date as date1 from <#Schema>.CampaignDates where datetype = 'Start' and campaignyear = <#CampaignYear> and orgaccountnumber = v.MANAGEDACCOUNT) d1,
(select cast(cast dateyear*1000 + datemonth*100 + dateday as varchar(255)) as date as date2 from <#Schema>.CampaignDates where datetype = 'End' and campaignyear = <#CampaignYear> and orgaccountnumber = v.MANAGEDACCOUNT) d2
from <#Schema>.VolunteerRelationships v
inner join <#Schema>.organizations o
on o.accountnumber=v.MANAGEDACCOUNT
where v.VOLUNTEERACCOUNT = <#SelectedInd> and ( v.EXPIRYDATE IS NULL OR v.EXPIRYDATE > <#Today> )

SQL Query to change the column format to row for each value

I have a query that fetches the data somewhat like -
#1
select
assignment_number,
ldg_name,
effective_start_date,
tax_reporting_name,
payroll_relationship_number,
filing_status,
allowance,
additional_tax_extra_withold,
exemp_fit,
exemp_medicare,
exemp_wage_accumulation,
exemp_unemployment
from
( SELECT PPRD.payroll_relationship_number,
PAAM.assignment_number,
PLDG.name
LDG_NAME,
To_char(PAAM.effective_start_date, 'YYYY-MM-DD')
effective_start_date,
(SELECT DISTINCT HOU.name
FROM pay_dir_rep_cards_f PDRCF,
hr_organization_units HOU,
pay_dir_rep_card_usages_f PDRCUF,
pay_rel_groups_dn PRGD1
WHERE PDRCF.dir_card_id = PDCF.dir_card_id
AND HOU.organization_id = PDRCF.tax_unit_id
AND PDRCUF.dir_rep_card_id = PDRCF.dir_rep_card_id
AND PRGD1.relationship_group_id =
PDRCUF.relationship_group_id
AND PDRCF.dir_card_comp_id = PDCCF2.dir_card_comp_id
AND trunc(sysdate) -11 BETWEEN PDRCF.effective_start_date AND
PDRCF.effective_end_date
AND trunc(sysdate) -11 BETWEEN
PRGD1.start_date AND PRGD1.end_date)
TAX_REPORTING_NAME,
(SELECT DISTINCT Decode (dir_information_char1, '1', 'Single',
'2', 'Married',
'3',
'Married and withholding at higher single rate'
FROM pay_dir_card_components_f PDCCF3,
pay_dir_comp_details_f PDCDF3
WHERE PDCCF3.dir_card_id = PDCF.dir_card_id
AND PDCCF3.dir_card_comp_id = PDCDF3.dir_card_comp_id
AND PDCDF3.dir_information_category =
'HRX_US_WTH_FEDERAL_INCOME_TAX'
AND trunc(sysdate) -11 BETWEEN PDCDF3.effective_start_date
AND
PDCDF3.effective_end_date)
FILING_STATUS,
exemp_fit,
PDFC.exemp_medicare,
PDFC.exemp_wage_accumulation,
PDFC.exemp_unemployment,
PDFC.exemp_social_security,
PDFC.regular_rate,
PDFC.regular_amount,
PDFC.supplemental_rate,
PDFC.supplemental_amt,
PDFC.irs_lock_in_date,
PDFC.statutory_employee,
PDFC.cumulative_taxation,
PDFC.primary_address,
PDFC.state_disability_calc,
PDFC.state_unemp_calc,
PDFC.qualifying_dependent,
PDFC.other_dependent,
PDFC.total_dependent,
PDFC.other_income,
PDFC.deduction_amount,
PDFC.max_federal_allowance ,
PDFC.allowance,
PDFC.additional_tax_extra_withold
from
per_all_assignments_m paam,
per_all_payroll_relationship PPRD,
per_legislative_table PLDG,
Per_cards PDCF,
Per_components PDFC
WHERE PAAM.ASSIGNMENT_NUMBER = PPRD.ASSIGNMENT_NUMBER
AND PPRD.LEGAL_UNIT = PLDG.LEGAL_UNIT
AND PDCF.dir_card_id = PDFC.dir_card_id
AND PDFC.ASSIGNMENT_ID = PAAM.ASSIGNMENT_ID
AND trunc(sysdate) -11 BETWEEN PAAM.effective_start_date
AND
PAAM.effective_end_date)
The above query is giving me the correct output in the format-
assignment_number ldg_name effective_start_date tax_reporting_name payroll_relationship_number filing_status allowance additional_tax_extra_withold exemp_fit exemp_medicare exemp_wage_accumulation exemp_unemployment
10 US 02-Aug-2020 Ontario 10-1 Single 1000 10 Y N
I need these columns in the format(Columns into rows) -
ASSIGNMENT_NUMBER ValueDefinitionName
10 filing_status
10 allowance
10 additional_tax_extra_withold
10 exemp_fit
10 exemp_medicare
i.e. the column names which ever is not null for an assignment_number.
Also, in the format ,
ASSIGNMENT_NUMBER ValueDefinitionName Value1
10 filing_status Single
10 allowance 1000
10 additional_tax_extra_withold 10
10 exemp_fit Y
10 exemp_medicare N
Since exemp_wage_accumulation and exemp_unemployment is null it should not be included.
Is there any way possible to achieve using my first query#1?
You should be able to use unpivot for this...
Here is a way to do this. I replaced the large query you got as a temp block with the appropriate data types--> data. You would need to replace the query that i have in the "data" block with the large query you got and also make sure that the datatypes for all of the columns you got is consistent (in this case all of the non-varchar columns are type casted to varchar)
After that you can use unpivot as follows
with data
as (select assignment_number
,ldg_name
,to_char(effective_start_date,'dd-mon-yyyy') as effective_start_date
,tax_reporting_name
,payroll_relationship_number
,filing_status
,to_char(allowance) as allowance
,to_char(additional_tax_extra_withold) as additional_tax_extra_withold
,exemp_fit
,exemp_medicare
,exemp_wage_accumulation
,exemp_unemployment
from t
)
select *
from data
unpivot (value1 for valuedefinitions in (
ldg_name
,effective_start_date
,tax_reporting_name
,payroll_relationship_number
,filing_status
,allowance
,additional_tax_extra_withold
,exemp_fit
,exemp_medicare
,exemp_wage_accumulation
,exemp_unemployment
)
)
+-------------------+------------------------------+-------------+
| ASSIGNMENT_NUMBER | VALUEDEFINITIONS | VALUE1 |
+-------------------+------------------------------+-------------+
| 10 | LDG_NAME | US |
| 10 | EFFECTIVE_START_DATE | 02-aug-2020 |
| 10 | TAX_REPORTING_NAME | Ontario |
| 10 | PAYROLL_RELATIONSHIP_NUMBER | 10-1 |
| 10 | FILING_STATUS | Single |
| 10 | ALLOWANCE | 1000 |
| 10 | ADDITIONAL_TAX_EXTRA_WITHOLD | 10 |
| 10 | EXEMP_FIT | Y |
| 10 | EXEMP_MEDICARE | N |
+-------------------+------------------------------+-------------+
Here is a db fiddle link
https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=9d211abbede82e276464333018a70731
You can try below method but it will work only if all columns except assignment number are of same type i.e. varchar or integer. You can have your main query as CTE.
Note: This is not a complete working query but just a hint to get you started.
with table1 as (...You existing query...)
SELECT ASSIGNMENT_NUMBER, "FILING_STATUS" AS VALUEDefinationname, filing_status as value1 from table1 where filing_status is not null
union
SELECT ASSIGNMENT_NUMBER, "allowance", allowance from table1 where allowance is not null

How to select company which have two groups

I still tried select all customers which is in two group. Duplicate from customers is normal because select is from invoice but I need to know the customers who had a group in the first half year and jumped to another in the second half year.
Example:
SELECT
f.eankod as kod, --(groups)
ad.kod as firma, --(markComp)
f.nazfirmy as nazev, --(nameComp)
COUNT(ad.kod),
sum(f.sumZklZakl + f.sumZklSniz + f.sumOsv) as cena_bez_dph --(Price)
FROM
ddoklfak as f
LEFT OUTER JOIN aadresar ad ON ad.idfirmy = f.idfirmy
WHERE
f.datvyst >= '2017-01-01'
and f.datvyst <= '2017-12-31'
and f.modul like 'FAV'
GROUP BY
f.eankod,
ad.kod,
f.nazfirmy
HAVING COUNT (ad.kod) > 1
order by
ad.kod
Result:
GROUP markcomp nameComp price
| D002 | B5846 | Cosmopolis | price ... |
| D003 | B6987 | Tismotis | price ... |
| D009 | B8974 | Teramis | price ... |
| D006 | B8876 | Kesmethis | price ... | I need this, same company but diferent group, because this
| D008 | B8876 | Kesmethis | price ... | company jumped. I need know only jumped company. (last two rows from examples)
Thx for help.
You can use a CTE to find out which nameComp show up multiple times, and keep those ones only. For example:
with
x as (
-- your query
)
select * from x where nameComp in (
select nameComp from x group by nameComp having count(*) > 1
)

how to get daily profit from sql table

I'm stucking for a solution at the problem of finding daily profits from db (ms access) table. The difference wrt other tips I found online is that I don't have in the table a field "Price" and one "Cost", but a field "Type" which distinguish if it is a revenue "S" or a cost "C"
this is the table "Record"
| Date | Price | Quantity | Type |
-----------------------------------
|01/02 | 20 | 2 | C |
|01/02 | 10 | 1 | S |
|01/02 | 3 | 10 | S |
|01/02 | 5 | 2 | C |
|03/04 | 12 | 3 | C |
|03/03 | 200 | 1 | S |
|03/03 | 120 | 2 | C |
So far I tried different solutions like:
SELECT
(SELECT SUM (RS.Price* RS.Quantity)
FROM Record RS WHERE RS.Type='S' GROUP BY RS.Data
) as totalSales,
(SELECT SUM (RC.Price*RC.Quantity)
FROM Record RC WHERE RC.Type='C' GROUP BY RC.Date
) as totalLosses,
ROUND(totalSales-totaleLosses,2) as NetTotal,
R.Date
FROM RECORD R";
in my mind it could work but obviously it doesn't
and
SELECT RC.Data, ROUND(SUM (RC.Price*RC.QuantitY),2) as DailyLoss
INTO #DailyLosses
FROM Record RC
WHERE RC.Type='C' GROUP BY RC.Date
SELECT RS.Date, ROUND(SUM (RS.Price*RS.Quantity),2) as DailyRevenue
INTO #DailyRevenues
FROM Record RS
WHERE RS.Type='S'GROUP BY RS.Date
SELECT Date, DailyRevenue - DailyLoss as DailyProfit
FROM #DailyLosses dlos, #DailyRevenues drev
WHERE dlos.Date = drev.Date";
My problem beyond the correct syntax is the approach to this kind of problem
You can use grouping and conditional summing. Try this:
SELECT data.Date, data.Income - data.Cost as Profit
FROM (
SELECT Record.Date as Date,
SUM(IIF(Record.Type = 'S', Record.Price * Record.Quantity, 0)) as Income,
SUM(IIF(Record.Type = 'C', Record.Price * Record.Quantity, 0)) as Cost,
FROM Record
GROUP BY Record.Date
) data
In this case you first create a sub-query to get separate fields for Income and Cost, and then your outer query uses subtraction to get actual profit.