How to cast to varchar and add % sign to SQL - sql

Ive been pulling my hair out to get around this..how can i convert this to a varchar and add the % symbol to the results?
I have placed the code below of the query and have tried to cast it but keep getting errors that i don't know how to fix. Can someone pleae make some suggestions on how to either simplify and prevent divide by zero issues also.
select 'Conversion Rate' as Type,
(
SELECT
(
COALESCE
(
CAST(CAST(nullif(t.ConvertedTrials,0) AS NUMERIC(18,2)) / (CAST(nullif(t.UnconvertedTrials,0) AS NUMERIC(18,2))) * 100 as decimal(10,2))
,
0
)
) AS Percentage
FROM (
SELECT
UnconvertedTrials = (
SELECT count(*) FROM
(
select memberid from membership where discountcodeid = '79a7fd7c-9ebe-4ec0-8ac0-95ea274f1f64' Group by membership.memberid
) as a
),
ConvertedTrials = (
SELECT count(*) FROM
(
SELECT membership.memberid
FROM Membership, Package
WHERE membership.PackageId = Package.Id
AND Package.PackageTypeId != 1
AND membership.memberid in (select memberid from membership where discountcodeid = '79a7fd7c-9ebe-4ec0-8ac0-95ea274f1f64')
Group by membership.memberid
) as b
)
) as t
) as Total

select 'Conversion Rate' as Type,
RTRIM(CAST((
SELECT
(
COALESCE
(
CAST(CAST(nullif(t.ConvertedTrials,0) AS NUMERIC(18,2)) / (CAST(nullif(t.UnconvertedTrials,0) AS NUMERIC(18,2))) * 100 as decimal(10,2))
,
0
)
) AS Percentage
FROM (
SELECT
UnconvertedTrials = (
SELECT count(*) FROM
(
select memberid from membership where discountcodeid = '79a7fd7c-9ebe-4ec0-8ac0-95ea274f1f64' Group by membership.memberid
) as a
),
ConvertedTrials = (
SELECT count(*) FROM
(
SELECT membership.memberid
FROM Membership, Package
WHERE membership.PackageId = Package.Id
AND Package.PackageTypeId != 1
AND membership.memberid in (select memberid from membership where discountcodeid = '79a7fd7c-9ebe-4ec0-8ac0-95ea274f1f64')
Group by membership.memberid
) as b
)
) as t
) AS NVARCHAR(50))) + '%' as Total
your actual percentage is quite a large sub-query, it's hard to see how to enclose it in brackets - I had about 10 goes - is it any good yet?
maybe it's easier to wrap the whole query in another select e.g
SELECT A,B FROM (<your query>) AS AQUERY
(which should give exactly same results as your query) - THEN work on formatting B in the outer query
Here is my second way of doing it
SELECT ORIGINAL.Type, RTRIM(CAST(ORIGINAL.Total as varchar(80))) + '%' AS Total
FROM
(
select 'Conversion Rate' as Type,
(
SELECT
(
COALESCE
(
CAST(CAST(nullif(t.ConvertedTrials,0) AS NUMERIC(18,2)) / (CAST(nullif(t.UnconvertedTrials,0) AS NUMERIC(18,2))) * 100 as decimal(10,2))
,
0
)
) AS Percentage
FROM (
SELECT
UnconvertedTrials = (
SELECT count(*) FROM
(
select memberid from membership where discountcodeid = '79a7fd7c-9ebe-4ec0-8ac0-95ea274f1f64' Group by membership.memberid
) as a
),
ConvertedTrials = (
SELECT count(*) FROM
(
SELECT membership.memberid
FROM Membership, Package
WHERE membership.PackageId = Package.Id
AND Package.PackageTypeId != 1
AND membership.memberid in (select memberid from membership where discountcodeid = '79a7fd7c-9ebe-4ec0-8ac0-95ea274f1f64')
Group by membership.memberid
) as b
)
) as t
) as Total
) ORIGINAL

Related

Join Fragment CTE to construct our proper table

This is my query
with cte as (
select mail
from dbo.reseau
where mail in
( select mail from dbo.reseau
group by mail
having count(1) > 1
) )
select * from (
select trig
from dbo.reseau
where trig in
( select trig from dbo.reseau
group by trig
having count(1) > 1
))t
select * from
(
select nom from reseau
where nom in (
( select nom from dbo.reseau
group by nom
having count(1) > 1
) ) )c
select * from (
select prenom from reseau
where prenom in (
( select prenom from dbo.reseau
group by prenom
having count(1) > 1)))r
I have 4 columns and I wrote this CTE to show duplicate data. My query shows them separately. I want to join them. How can I do this?
If you want rows where any of the columns contain duplicate values, you can use window functions multiple times:
select *
from (
select
r.*,
count(*) over(partition by mail) cnt_mail,
count(*) over(partition by trig) cnt_trig,
count(*) over(partition by nom) cnt_nom,
count(*) over(partition by prenom) cnt_prenom
from reseau
) t
where cnt_mail > 1 or cnt_trig > 1 and cnt_nom > 1 end cnt_prenom > 1
The where clause can be simplified as:
where cnt_email + cnt_trig + cnt_nom + cnt_prenom > 4

How to divide the count() of two seperate queries in DB2

So I have
select count(*) from ( "query1")
select count(*) from ( "query2")
I want to divide the two and get the floating point result.
I was told to use something like this
SELECT (COUNT(smtg) * 1.0) / COUNT(smtg)
But Im not sure
You can just do:
select q1.cnt * 1.0 / q2.cnt
from (select count(*) as cnt from ( "query1") ) q1 cross join
(select count(*) as cnt from ( "query2") ) q2;
Or, if you prefer:
select ( (select count(*) from ( "query1")) * 1.0 /
(select count(*) from ( "query2"))
)
from sysibm.sysdummy1;
other solution (be carefull to not divide by 0)
with
query1 as (select count(*) as nb1 from ( "query1")),
query2 as (select count(*) as nb2 from ( "query2"))
select case when nb2=0 then null else nb1* 1.0/nb2 end as Result
from query1, query2

How to call a sql query and pass a parameter from another table?

I have a complex sql query, named qryARAT2B_EXT.
SELECT
*
FROM
(
SELECT
*
FROM
(
SELECT
*,
firstStudy,
ABS(DATEDIFF('d', firstStudy, Check_Date)) as diff
FROM
(
SELECT
*,
(
SELECT
TOP 1 Check_Date
FROM
qryARAT2B
WHERE
PATNR = [PАРАМ]
ORDER BY
Check_Date
)
AS firstStudy
FROM
(
SELECT
*
FROM
qryARAT2B
WHERE
PATNR = [PАРАМ]
)
AS myPatientsWithStudy
)
AS myPatientsFirstStudy
)
WHERE
diff = 0
)
AS T1
LEFT JOIN
(
SELECT
*
FROM
(
SELECT
*,
firstStudy,
ABS(DATEDIFF('d', firstStudy, Check_Date)) as diff
FROM
(
SELECT
*,
(
SELECT
TOP 1 Check_Date
FROM
qryARAT2B
WHERE
PATNR = [PАРАМ]
ORDER BY
Check_Date
)
AS firstStudy
FROM
(
SELECT
*
FROM
qryARAT2B
WHERE
PATNR = [PАРАМ]
)
AS myPatientsWithStudy
)
AS myPatientsFirstStudy
)
WHERE
diff = 4
)
As T2
ON T1.PATNR = T2.PATNR
When I open it in ms-access, it asks for the value of the [PARAM] and produces the result.
I have a table of patients.
tblPatient with the columns:
PATNR, and s.o.
That contains the PATNR's of patients:
000001
000002
...
XXXXXX
I need to write sql to calculate data for all PATNR's at once.
something like this:
SELECT (SELECT * FROM qryARAT2B_EXT WHERE [PARAM] = PATNR) from tblPatient
But it is not accepted from ms-access. I'm not able to pass parameter to qryARAT2B_EXT from the SQL. Is there any specific syntax for it in ms-access?

how to do math on results from two querys

i have to results that came from each query
first query:
SELECT [xcv], COUNT( * ) AS Total
FROM [my_table]
GROUP BY [xcv]
second query:
SELECT [xcv], COUNT( * ) AS Total
FROM [my_table]
WHERE=[result]='ok'
GROUP BY [xcv]
what i want to do is to get the value of -> [ (first_query/second query) *100 ]
And i want results for each [xcv] in my table...
any idea how i can do it ?
thank you all
SELECT t1.[xcv],
(t1.total/t2.total)*100
FROM (SELECT [xcv],
COUNT( * ) AS Total
FROM [my_table]
GROUP BY
[xcv]
) t1 JOIN (
SELECT [xcv],
COUNT( * ) AS Total
FROM [my_table]
WHERE [result]='ok'
GROUP BY
[xcv]
) t2
ON t1.[xcv]=t2.[xcv]
I also removed the = sign from WHERE=[result]='ok' - I think you mistyped it in.
One query:
SELECT [xcv],
(SUM(CASE
WHEN [result] = 'ok'
THEN 1
ELSE 0
END
)/COUNT( * )
) * 100
FROM [my_table]
GROUP BY [xcv]

is there an easier way than doing UNION ALL?

I have a rather large query which select data from a certain date range.
I would like to group data based on year.
Right now I have:
;with mappingTable as
(
select b.CLIENT_ID,f.patient_id,f.received_date,f.SPECIMEN_ID
from F_ACCESSION_DAILY f
join
(
select f.client_id,a.patient_id
from
(
SELECT
max(received_date) AS received_date
, patient_id AS Patient_ID
FROM F_ACCESSION_DAILY
group by PATIENT_ID
) a
join F_ACCESSION_DAILY f
on f.PATIENT_ID=a.Patient_ID
and f.RECEIVED_DATE=a.received_date
) b
on b.Patient_ID=f.PATIENT_ID
where f.RECEIVED_DATE between '20100101' and '20110101' - as you can see this data is only for 2010
) ---there's much more to this query
as you can see this data is only for 2010
but i would like to do union all for all years: 2008, 2009, 2010, 2011, 2012...
how do i do this without rewriting the query 5 times and doing a union all between all of them?
here's the entire monster query:
;with mappingTable as
(
select b.CLIENT_ID,f.patient_id,f.received_date,f.SPECIMEN_ID
from F_ACCESSION_DAILY f
join
(
select f.client_id,a.patient_id
from
(
SELECT
max(received_date) AS received_date
, patient_id AS Patient_ID
FROM F_ACCESSION_DAILY
group by PATIENT_ID
) a
join F_ACCESSION_DAILY f
on f.PATIENT_ID=a.Patient_ID
and f.RECEIVED_DATE=a.received_date
) b
on b.Patient_ID=f.PATIENT_ID
where f.RECEIVED_DATE between '20100101' and '20110101'
)
,
counted as(
SELECT
PATIENT_ID,
client_id,
--case when COUNT(*)>=12 then 12 else COUNT(*) end TimesTested,
COUNT(*) as timestested,
case when count(*)>1 then
(datediff(day,MIN(received_date),max(received_date)))
/(COUNT(*)-1)
else
0
end as testfreq
FROM mappingTable
GROUP BY
client_id,
patient_id
),counted2 as (
SELECT
client_id,
TimesTested,
CAST(COUNT(*) AS varchar(30)) AS count,
CAST(AVG(testfreq) as varchar(30)) as TestFreq,
CAST(STDEV(TestFreq) as varchar(30)) Stdv
FROM counted
GROUP BY
client_id,
TimesTested
),
counted3 as
(
SELECT
patient_id,
client_id,
TimesTested,
CAST(COUNT(*) AS varchar(30)) AS count,
AVG(testfreq) as TestFreq
FROM counted
GROUP BY
client_id,
TimesTested,
PATIENT_ID
)
,
CountOver12 as
( select client_id,count(*) count
from counted
where timestested>12
group by CLIENT_ID)
,
TotalAvgTestFreq as (
select client_id, SUM(testfreq) / count(testfreq) TotalAvgTestFreq
from counted3
group by client_id
)
,
unpivoted AS (
SELECT
client_id,
ColumnName + CAST(TimesTested AS varchar(10)) AS ColumnName,
ColumnValue
FROM counted2
UNPIVOT (
ColumnValue FOR ColumnName IN (count, TestFreq,stdv)
) u
),
pivoted AS (
SELECT
client_id clientid,
count1, TestFreq1,stdv1,
count2, TestFreq2,stdv2,
count3, TestFreq3,stdv3,
count4, TestFreq4,stdv4,
count5, TestFreq5,stdv5,
count6, TestFreq6,stdv6,
count7, TestFreq7,stdv7,
count8, TestFreq8,stdv8,
count9, TestFreq9,stdv9,
count10, TestFreq10,stdv10,
count11, TestFreq11,stdv11,
count12, TestFreq12,stdv12
FROM unpivoted
PIVOT (
MAX(ColumnValue) FOR ColumnName IN (
count1,TestFreq1,stdv1,
count2,TestFreq2,stdv2,
count3,TestFreq3,stdv3,
count4,TestFreq4,stdv4,
count5,TestFreq5,stdv5,
count6,TestFreq6,stdv6,
count7,TestFreq7,stdv7,
count8, TestFreq8, stdv8,
count9, TestFreq9, stdv9,
count10, TestFreq10,stdv10,
count11, TestFreq11,stdv11,
count12, TestFreq12,stdv12
)
) p
)
,
PatientStats as
(
select
distinct
f.client_id
,datediff(MM,c.mlis_date_established,GETDATE()) MonthsCustomer
,count(distinct patient_id) TotalPatients
,count(distinct specimen_id) TotalSpecimens
from mappingTable f
left join D_CLIENT c
on f.CLIENT_ID=c.CLIENT_ID
group by f.client_id,c.mlis_date_established
)
,
Over12
as
(
select client_id,SUM(c) sumcount from
(
select CLIENT_ID,COUNT(*) c
from mappingTable
group by CLIENT_ID,PATIENT_ID
having count(*)>12
) a
group by client_id
),
GetMedian as(
select client_id, avg(timestested) median_testfreq
from
(
select client_id,
timestested,
rn=row_number() over (partition by CLIENT_ID
order by timestested),
c=count(timestested) over (partition by CLIENT_ID)
from counted3
where timestested>1
) g
where rn in (round(c/2,0),c/2+1)
group by client_id
)
, final as (
SELECT p.*,pivoted.*,c12.count [Count13+],Over12.sumcount SumofGreaterThan12,t.TotalAvgTestFreq,median.median_testfreq
FROM pivoted
left join PatientStats p
on p.CLIENT_ID=pivoted.CLIENTID
left join Over12
on over12.CLIENT_ID=p.CLIENT_ID
left join TotalAvgTestFreq t
on t.CLIENT_ID=p.CLIENT_ID
left join CountOver12 C12
on c12.CLIENT_ID=p.CLIENT_ID
left join GetMedian median
on median.CLIENT_ID=p.CLIENT_ID
where p.CLIENT_ID not in (select CLIENTid from SalesDWH..TestPractices)
)
/* Get the data into a temp table */
SELECT * INTO #TempTable
FROM final
/* Drop the cloumns that are not needed */
ALTER TABLE #TempTable
DROP COLUMN clientid
/* Get results and drop temp table */
SELECT * FROM #TempTable
DROP TABLE #TempTable
Create a table function:
CREATE FUNCTION fn_get_data_by_date_range
(
#start AS VARCHAR(8),
#end AS VARCHAR(8)
)
RETURNS TABLE
AS
RETURN
(
...your query...
WHERE f.RECEIVED_DATE BETWEEN #start AND #end
)
then you can UNION different call of that function:
SELECT * FROM fn_get_data_by_date_range('20100101','20110101')
UNION ALL
SELECT * FROM fn_get_data_by_date_range('20090101','20100101')
UNION ALL
....
UNION ALL
SELECT * FROM fn_get_data_by_date_range('20070101','20080101')