Migrate if statement from mysql to firebird - firebird2.5

SELECT if((a.status is null)or(a.status='')or(a.status='-'),'Not Submitted Yet',a.status) as OBJ1, 'Cummulative Progress' as obj2, a.project_id, gp.team_name,
COUNT(DISTINCT(a.task_id)) as NILAI
FROM task a INNER JOIN
site b ON a.site_id=b.site_id LEFT OUTER JOIN
task_privilige pv ON a.task_id = pv.task_id LEFT OUTER join
team gp on pv.team_id = gp.team_id LEFT OUTER join
task_tenant f ON a.task_id = f.task_id
WHERE 1 ".$xqr."
GROUP BY OBJ1, a.ID, a.PROJECT_ID, a.TASK_ID, a.PHASE, a.SITE_ID, a.ATTACHMENT_FILE, a.PLAN_DATE, a.BAPP, a.STATUS, a.REMARK, a.TASK_TYPE, a.LAST_UPDATE, a.LAST_UPDATER_ID, a.TASK_ID_REFERENCE, a.SOURCE_SITE_ID, a.DESTINATION, a.VENDOR, a.ADMIN_ID, a.ENGINEER_ID, a.MATERIAL_ID, a.REMARK_CHECKER, a.TAG_CHECK, a.TAG_MANUAL,
b.ID, b.SITE_NAME, b.PERIODE, b.SITE_ID, b.TYPE_SITE, b.BSC, b.ADDRESS, b.AREA, b.CITY, b.LAT, b.LANG, b.RADIUS, b.KETERANGAN, b.LAST_UPDATE, b.LAST_UPDATER_ID,
pv.ID, pv.TASK_ID, pv.TEAM_ID, pv.LAST_UPDATE, pv.LAST_UPDATER_ID,
gp.ID, gp.TEAM_ID, gp.TEAM_NAME, gp.TEAM_LEADER_ID, gp.LAST_UPDATE, gp.LAST_UPDATER_ID,
f.ID, f.TASK_ID, f.TENANT_NAME, f.TENANT_TYPE

You can use CASE:
CASE WHEN a.status IS NULL OR a.status = '' OR a.status = '-'
THEN 'Not Submitted Yet'
ELSE a.status
END AS OBJ1
Or you can use IIF:
IIF(a.status IS NULL OR a.status = '' OR a.status = '-',
'Not Submitted Yet', a.status) AS OBJ1

Related

How to add round brackets to TypeORM's QueryBuilder .from(subquery) method?

I am using QueryBuilder and I need to make a from from SQL function. I am using subqueries, but there is a problem: when I create a SQL query, the round brackets are not created for upc subquery:
qb.leftJoin(
subQuery => {
if (sortOption === TherapistAdminSort.UPCOMING_SESSIONS) {
subQuery
.select('upcoming.id', 'therapistId')
.addSelect('count(*)', 'upcomingSessionsCount')
.from((upc) => {
return upc
.createQueryBuilder()
.select('t.id', 'id')
.addSelect('s.patientId', 'patientId')
.from('therapists', 't')
.withDeleted()
.innerJoin(s => {
return s.select('*')
.from(`get_sessions_by_therapist_id(t.id, now())`, 's2');
}, 's', 's."therapistId" = t.id')
.groupBy('t.id')
.addGroupBy('s."patientId"');
}, 'upcoming')
.groupBy('upcoming.id');
}
return subQuery;
},
'grouped',
'therapist.id = grouped."therapistId"',
)
This query below produces following LEFT JOIN:
LEFT JOIN (SELECT upcoming.id AS "therapistId", count(*) AS "upcomingSessionsCount"
FROM SELECT t.id AS id, s.patientId AS "patientId"
FROM therapists t
INNER JOIN (SELECT * FROM get_sessions_by_therapist_id(t.id, now()) s2) s ON s."therapistId" = t.id
GROUP BY t.id, s."patientId" upcoming
GROUP BY upcoming.id) grouped ON therapist.id = grouped."therapistId"
As you can see, there is no round brackets produced.

how to pass string value in `find_by_sql`

Using query like:
Campaign.find_by_sql("select c.*,sc.*,org.name as org_name from campaigns as c left join super_campaigns as sc ON sc.id= c.super_campaign_id left join organisations as org ON org.id= c.organisation_id where c.status=0 AND sc.status='active'")
Getting error after using sc.status='active'.Thanks.
You can achieve that by using interpolation, here is an example from a project i made for doing something similar
self.find_by_sql("SELECT s.subject_title AS subject_name,s.subject_code AS subject_code,
COUNT(*) AS total_complaints,
COUNT(CASE p.priority_name WHEN '#{Ticket::HIGH}' THEN 1 END) AS high_complaints,
COUNT(CASE p.priority_name WHEN '#{Ticket::NORMAL}' THEN 1 END) AS normal_complaints,
COUNT(CASE p.priority_name WHEN '#{Ticket::LOW}' THEN 1 END) AS low_complaints
FROM
tickets AS t
JOIN
subjects AS s
ON t.subject_id = s.id
JOIN
priorities AS p
ON t.priority_id = p.id
WHERE
p.priority_name IN ('#{Ticket::HIGH}', '#{Ticket::NORMAL}', '#{Ticket::LOW}')
GROUP BY s.subject_title, s.subject_code
ORDER BY total_complaints ASC")
As you can see #{Ticket::HIGH} is coming from PRIORITY = [HIGH = 'high', NORMAL = 'normal', LOW = 'low'] same goes for the others
Note: this is a part of the original code.

What does this error mean for this massive postgresql statement in a Rails 4 app?

I have the following massive sql statement executing in a Rails 4 application via the usual ActiveRecord query helpers (where, join)..Products are distinguished via unique database id.
SELECT
subscriptions.braintree_account_id as braintree_account_id,
subscriptions.braintree_subscription_id as braintree_subscription_id,
format('%s %s', addresses.first_name, addresses.last_name) as shipping_address_full_name,
users.email as email,
addresses.line_1 as shipping_address_line_1,
addresses.line_2 as shipping_address_line_2,
addresses.city as shipping_address_city,
addresses.state as shipping_address_state,
addresses.zip as shipping_address_zip_code,
addresses.country as shipping_address_country,
CASE WHEN tiger_shirt IS NULL THEN '' ELSE tiger_shirt END,
CASE WHEN tiger_socks IS NULL THEN '' ELSE tiger_socks END,
CASE WHEN tiger_accessories IS NULL THEN '' ELSE tiger_accessories END,
CASE WHEN tiger_waist IS NULL THEN '' ELSE tiger_waist END,
CASE WHEN tiger_tail_shirt IS NULL THEN '' ELSE tiger_tail_shirt END,
CASE WHEN tiger_tail_socks IS NULL THEN '' ELSE tiger_tail_socks END,
CASE WHEN tiger_tail_waist IS NULL THEN '' ELSE tiger_tail_waist END,
CASE WHEN tiger_tshirt IS NULL THEN '' ELSE tiger_tshirt END,
CASE WHEN tiger_accessories_waist IS NULL THEN '' ELSE tiger_accessories_waist END,
CASE WHEN tiger_ta_tail_shirt IS NULL THEN '' ELSE tiger_ta_tail_shirt END,
CASE WHEN tiger_ta_tail_waist IS NULL THEN '' ELSE tiger_ta_tail_waist END,
plans.name as plan_name,
products.sku as sku,
to_char(subscriptions.created_at, 'MM/DD/YYYY HH24:MM:SS') as subscription_created_at,
to_char(subscriptions.next_assessment_at, 'MM/DD/YYYY HH24:MM:SS') as subscription_next_assessment_at,
subscriptions.subscription_status as subscription_status
FROM
"subscriptions"
INNER JOIN
"addresses"
ON "addresses"."id" = "subscriptions"."shipping_address_id"
AND "addresses"."type" IN ('ShippingAddress')
LEFT OUTER JOIN
shipping_methods
ON shipping_methods.subscription_id = subscriptions.id
LEFT OUTER JOIN
plans
ON subscriptions.plan_id = plans.id
LEFT OUTER JOIN
users
ON subscriptions.user_id = users.id
LEFT OUTER JOIN
products
ON plans.product_id = products.id
LEFT OUTER JOIN
(SELECT * FROM crosstab('SELECT
subscriptions.id,
choice_types.id,
value_choices.presentation
FROM
subscriptions
LEFT JOIN
subscription_variables
ON subscriptions.id = subscription_variables.subscription_id
LEFT JOIN
variables
ON subscription_variables.variable_id=variables.id
LEFT JOIN
value_choice_variables
ON variables.id=value_choice_variables.variable_id
LEFT JOIN
value_choices
ON value_choice_variables.value_choice_id=value_choices.id
LEFT JOIN
choice_types
ON value_choices.choice_type_id=choice_types.id
LEFT JOIN
choice_type_products
ON choice_type_products.choice_type_id=choice_types.id
LEFT JOIN
products
ON choice_type_products.product_id = products.id
WHERE
products.id IN (2, 3, 4, 11, 12, 15)
ORDER BY 1,2',
'SELECT
choice_types.id
FROM
choice_types
JOIN
choice_type_products
ON choice_type_products.choice_type_id = choice_types.id
JOIN
products
ON choice_type_products.product_id = products.id
WHERE
products.id IN (2, 3, 4, 11, 12, 15)
ORDER BY
choice_types.id ASC')
AS (
subscription_id int,
tiger_shirt VARCHAR,
tiger_socks VARCHAR,
tiger_accessories VARCHAR,
tiger_waist VARCHAR,
tiger_tail_shirt VARCHAR,
tiger_tail_waist VARCHAR,
tiger_tail_socks VARCHAR,
tiger_tshirt VARCHAR,
tiger_accessories_waist VARCHAR,
tiger_ta_tail_shirt VARCHAR,
tiger_ta_tail_waist VARCHAR
)
) subscription_variable_view
ON subscriptions.id=subscription_variable_view.subscription_id
WHERE
"subscriptions"."subscription_status" = $1 AND
"addresses"."flagged_invalid_at" IS NULL AND
"products"."id" IN (2, 3, 4, 11, 12, 15) AND
(NOT EXISTS (
SELECT
"subscription_hunted_months".*
FROM
"subscription_hunted_months"
WHERE
"subscription_hunted_months"."month_year" = 'JUN2016' AND
subscription_hunted_months.subscription_id = subscriptions.id))
I get the following error when it tries to run...what does it mean? And what could be causing it?
ActiveRecord::StatementInvalid: PG::DuplicateObject: ERROR: duplicate category name
It's likely that your CATEGORY SQL argument is returning duplicate values:
SELECT
choice_types.id
FROM
choice_types
JOIN
choice_type_products
ON choice_type_products.choice_type_id = choice_types.id
JOIN
products
ON choice_type_products.product_id = products.id
WHERE
products.id IN (2, 3, 4, 11, 12, 15)
ORDER BY
choice_types.id ASC
If you simply made it DISTINCT and reran you query - it may resolve the issue.
SELECT DISTINCT
choice_types.id
...

Why I cannot use both ORDER BY and DISTINCT * in SQL?

I'm trying to do the following, and if I were to uncomment the distinct it will break. Also if I comment out the order and leave the distinct in, it will work.
Contestant.joins('INNER JOIN votes AS V ON V.contestant_id = contestants.id AND V.season_id = '+ season_number.to_s)
.joins('LEFT OUTER JOIN votes AS XV ON (XV.contestant_id = '+self.id.to_s+') AND (XV.tribal_council_key = V.tribal_council_key) AND XV.contestant_voted_for_id = V.contestant_voted_for_id')
.joins('INNER JOIN season_rosters ON season_rosters.season_id = V.season_id')
.where('V.is_jury_vote = (?) AND V.contestant_id <> (?) AND XV.tribal_council_key IS NOT NULL', :false, self.id)
.order('season_rosters.finished')
#.distinct
The error I get is below...
TinyTds::Error: Incorrect syntax near '*'.: EXEC sp_executesql N'SELECT DISTINCT *, __order FROM ( SELECT [contestants].*, DENSE_RANK() OVER (ORDER BY season_rosters.finished ASC) AS __order, ROW_NUMBER() OVER (PARTITION BY [contestants].* ORDER BY season_rosters.finished ASC) AS __joined_row_num FROM [contestants] INNER JOIN votes AS V ON V.contestant_id = contestants.id AND V.season_id = 6 LEFT OUTER JOIN votes AS XV ON (XV.contestant_id = 112) AND (XV.tribal_council_key = V.tribal_council_key) AND XV.contestant_voted_for_id = V.contestant_voted_for_id INNER JOIN season_rosters ON season_rosters.season_id = V.season_id WHERE (V.is_jury_vote = (''false'') AND V.contestant_id <> (112) AND XV.tribal_council_key IS NOT NULL) ) AS __sq WHERE __joined_row_num = 1 ORDER BY __order'
The issue is with this part:
SELECT DISTINCT *, __order
Try adding the required columns to your GROUP BY.
Contestant.joins('INNER JOIN votes AS V ON V.contestant_id = contestants.id AND V.season_id = '+ season_number.to_s)
.joins('LEFT OUTER JOIN votes AS XV ON (XV.contestant_id = '+self.id.to_s+') AND (XV.tribal_council_key = V.tribal_council_key) AND XV.contestant_voted_for_id = V.contestant_voted_for_id')
.joins('INNER JOIN season_rosters ON season_rosters.season_id = V.season_id')
.where('V.is_jury_vote = (?) AND V.contestant_id <> (?) AND XV.tribal_council_key IS NOT NULL', :false, self.id)
.order('season_rosters.finished')
.group('col1,col2,__order')
Also in your SQL error, order by is on a different column while in your code, it is on season_rosters.finished.

Rake Tasks With Tiny_TDS

I'm trying to access some data from our on-site billing server to be populate into a rails app that i'm deploying. I've done some digging about and think Tiny TDS and a rake task is the best way to go but I seem to be getting a bit stuck. The code showed below is just an example and not finished! I keep getting a server name not found in configuration files error.
task :import_customers do
RAILS_HOME = File.expand_path(File.join(File.dirname(__FILE__),"../.."))
RAILS_CONFIG = "#{RAILS_HOME}/config"
require "#{RAILS_CONFIG}/environment"
require 'tiny_tds'
client = TinyTds::Client.new(:username => 'user', :password => 'pass', :host => 'SQLSRVR')
result = client.execute("select sitedetails.siteid, company.id as companyid, sitedetails.shortname, company.name,sitedetails.sitename as [Site Name] from company inner join sitedetails on company.id=sitedetails.id left outer join solutionscustinfo s on sitedetails.siteid=s.siteid left outer join paymentconditions a on s.paymentconditions_id=a.id left outer join company agent on company.agent_id=agent.id left outer join sitecontacts billingcontact on billingcontact.contactid=s.billingcontact_id left outer join package p on p.id=package left outer join tariffnames v on v.tariffcode=isnull(s.lcr_tariff,p.lcr_tariff) left outer join tariffnames d on d.tariffcode=isnull(s.data_tariff,p.data_tariff) left outer join tariffnames m on m.tariffcode=isnull(s.mob_tariff,p.mob_tariff) left outer join (select invoiceaddress from sitedetails group by invoiceaddress) ba on ba.invoiceaddress=sitedetails.siteid left outer join discount on discount.id=isnull(s.discount,p.discount) left outer join billrun on billrun.id=s.bill_run left outer join report_profile on report_profile.id=s.report_profile left outer join account_manager on account_manager.id=company.acctmgr_id where company.is_customer<>0 order by company.name,sitedetails.shortname")
result.each do |row|
puts row
name = row['name']
sitename = row['Site Name']
puts sitename
#company = Company.all
end
end
Sorry for not replying I went about this in a different way in the end.
namespace :abillity do
desc "import customers"
def return_address(siteid)
client = TinyTds::Client.new(:username => 'earth', :password => 'gs500e', :host => '192.168.1.38')
result = client.execute("select Address, Town, County, PostCode from sitedetails WHERE SiteID = '#{siteid}'")
result.each do |row|
if (row['Address'] == nil or row['Town'] == nil or row['County'] == nil or row['PostCode'] == nil)
return "Not Listed"
end
#address = row['Address'] + " " + row['Town'] + " " + row['County'] + " " + row['PostCode']
if (#address == nil)
return "Not Listed"
elsif (#address.strip == "")
return "Not Listed"
else
return #address
end
return ""
end
end
task :import_customers => :environment do
require 'tiny_tds'
require 'rubygems'
client = TinyTds::Client.new(:username => 'earth', :password => 'gs500e', :host => '192.168.1.38')
result = client.execute("select sitedetails.siteid, company.id as companyid, sitedetails.shortname, company.name,sitedetails.sitename as [Site Name],sitedetails.sage_id as [Account No] from company inner join sitedetails on company.id=sitedetails.id left outer join solutionscustinfo s on sitedetails.siteid=s.siteid left outer join paymentconditions a on s.paymentconditions_id=a.id left outer join company agent on company.agent_id=agent.id left outer join sitecontacts billingcontact on billingcontact.contactid=s.billingcontact_id left outer join package p on p.id=package left outer join tariffnames v on v.tariffcode=isnull(s.lcr_tariff,p.lcr_tariff) left outer join tariffnames d on d.tariffcode=isnull(s.data_tariff,p.data_tariff) left outer join tariffnames m on m.tariffcode=isnull(s.mob_tariff,p.mob_tariff) left outer join (select invoiceaddress from sitedetails group by invoiceaddress) ba on ba.invoiceaddress=sitedetails.siteid left outer join discount on discount.id=isnull(s.discount,p.discount) left outer join billrun on billrun.id=s.bill_run left outer join report_profile on report_profile.id=s.report_profile left outer join account_manager on account_manager.id=company.acctmgr_id where company.is_customer<>0 order by company.name,sitedetails.shortname")
result.each do |row|
# First of all check if a company allready exists that has the same name and site name
existing = Company.where(["name = ?",row['name']]).where(["site = ?",row['Site Name']]).limit(1)
if (row['Account No'] == nil or row['Account No'] == "")
row['Account No'] = "N/A"
end
if (existing.first == nil)
# Company does not exist add it
#company = Company.new
#company.name = row['name']
#company.site = row['Site Name']
#company.accountNumber = row['Account No']
#company.address = return_address(row['siteid'])
#company.companytype = "Customer"
if (#company.save! == false)
debugger
end
else
# Existing, make sure acct no and address is up to date
#company = existing[0]
#company.accountNumber = row['Account No']
#company.address = return_address(row['siteid'])
#company.save
end
end
end
end

Resources