Create a Query to Combine Data from Two Tables with Similar data - sql-server-2012

In need an aggregate result of two similar tables without getting duplicates.
The tables have similar structure. (date,billed_number,carrier_id,duration...)
tables are 2019-01-29 and 2019-01-30
I've tried UNION of the same query but I get duplicate entries.
select billed_number, sum(CASE WHEN [account_billed_duration] > 0 THEN 1 END) AS completed
from alex4..[2019-01-29]
where billed_number = '702640'
and carrier_id = 171
group by billed_number
union all
select billed_number, sum(CASE WHEN [account_billed_duration] > 0 THEN 1 END) AS completed
from alex4..[2019-01-30]
where billed_number = '702640'
and carrier_id = 171
group by billed_number
In this example I'm only using tables ([2019-01-29] and [2019-01-30])
I also need to be able to combine more than two tables.
Result:
billed_number,completed
702640 3735
702640 3539
Expected Result:
billed_number, completed
702640 7274

Use union not union all indeed combine all results with duplicates

thank you for the reply. I actually tried both UNION and UNION ALL and got the same result.
I was up last night until I figured it out.
A sub query did the trick...
SELECT distinct billed_number , sum(completed)as comp , FROM (
SELECT [billed_number],
sum(CASE WHEN [account_billed_duration] > 0 THEN 1 END) AS completed,
sum(CASE WHEN [account_billed_duration] = 0 THEN 1 END) AS failed
FROM alex4..[2019-01-29]
where billed_number = '702640'
and carrier_id = 171
group by billed_number --,account_billed_duration
UNION
SELECT [billed_number],
sum(CASE WHEN [account_billed_duration] > 0 THEN 1 END) AS completed,
sum(CASE WHEN [account_billed_duration] = 0 THEN 1 END) AS failed
FROM alex4..[2019-01-30]
where billed_number = '702640'
and carrier_id = 171
group by billed_number --, account_billed_duration
) Q
group by billed_number
Once again thank you for the reply :-)

Related

Using SQL, how to calculate count of rows for each ID(column) for each month by using only datetime and put them in monthly columns?

I am relatively new to SQL. I have a dataset as follows:
'ID' 'date'
1 2016-01-01 01:01:06
2 2016-01-02 02:02:07
1 2016-01-03 03:03:08
3 2016-04-04 04:04:09
2 2016-04-05 05:05:00
I want to obtain smth like this:
'ID' 'Count: Jan' 'Count: Feb' 'Count: March' 'Count: April'
1 2 0 0 0
2 1 0 1 0
3 0 0 0 1
I really have no idea how handle this. I could put the data creating a column "month" and another column "count" but I want to be able to have a table like this.
Thanks in advance
You ca use conditional aggregation:
select id,
sum(case when month(date) = 1 then 1 else 0 end) as cnt_jan,
sum(case when month(date) = 2 then 1 else 0 end) as cnt_feb,
. . .
sum(case when month(date) = 12 then 1 else 0 end) as cnt_dec
from t
group by id;

how to sum two column within single case statement

The query below returns 2 rows, but actually I need only one;
select Datename(month, m.CreatedDate) as [Ay], sum(case when h.Cinsiyet=1 then 1 else 0 end) as [Group1], sum(case when h.Cinsiyet=2 then 1 else 0 end) as [Group2] from Muayene.Muayene m with(nolock)
join Ortak.Hasta h with(nolock) on m.HastaTc = h.HastaTc
group by h.Cinsiyet, Datename(month, m.CreatedDate)
result:
MonthName Group1 Group2
April 4500 0
April 0 9000
Expected Result:
MonthName Group1 Group2
April 4500 9000
I know I can do it wrapping the query with another select statement and Group by month and Sum these results.. But its not efficient and looks dirty code.
How can I make a trick to get expected result without make another sum statement?
FIx the GROUP BY:
select Datename(month, m.CreatedDate) as [Ay],
sum(case when h.Cinsiyet = 1 then 1 else 0 end) as [Group1],
sum(case when h.Cinsiyet = 2 then 1 else 0 end) as [Group2]
from Muayene.Muayene m join
Ortak.Hasta h
on m.HastaTc = h.HastaTc
group by Datename(month, m.CreatedDate);

infuse a sum of the value in the another column with a different filter than the total count column

First here's a sample table.
enter image description here
Provider_name patient date status length
AF AGUIR00001 07/05/2018 3 30
AF ABBOT00001 07/05/2018 30
BB ADAMS00001 07/05/2018 3 30
BB ACEVE00001 07/06/2018 3 30
I have created a query that lets me count the total number of appointments versus the number of appointments with a certain status(eg checked out). I was able to create it and group it by provider.
select provider_name,
count(patient) total,
sum(case when status = 3 then 1 else 0 end) as Checkedout
from appointment
group by provider_name
Then I moved on to the next phase which was to get the total length of those appointments with checkedout status. I made this query but it does not break down into each provider.
select provider_name,
count(patient) total,
sum(case when status = 3 then 1 else 0 end) as Checkedout,
(select sum(length) from appointment where status = 3
and date between '06/01/2018' and '07/06/2018')
from appointment where date between '06/01/2018' and '07/06/2018'
group by provider_name
I need it so that the last column in the query is segregated per provider_name.
Thank you in advance for helping me out.
Actually, you were on the right way, try this:
select provider_name,
count(patient) total,
sum(case when status = 3 then 1 else 0 end) as Checkedout,
sum(case when status = 3 then length else 0 end) as len_status3
from appointment
where date between '2018-01-06' and '2018-06-07'
group by provider_name;
According to your last comment, you need a WITH ROLLUP modifier for GROUP BY as in the following :
select coalesce(provider_name,'Total') as provider_name,
count(patient) total,
sum(case when status = 3 then 1 else 0 end) as Checkedout,
sum(case when status = 3 then length else 0 end) as len_status3
from appointment
where date between '2018-01-06' and '2018-06-07'
group by provider_name with rollup;
SQL Fiddle Demo
you shoul do as for checkedoutout
select provider_name,
count(patient) total,
sum(case when status = 3 then 1 else 0 end) as Checkedout,
sum( case when status = 3 then length else 0 ) as total_length
from appointment where date between '06/01/2018' and '07/06/2018'
group by provider_name

Group by datepart and find total count of individual values of each record

This is table structure;
ID Score Valid CreatedDate
1 A 1 2018-02-19 23:33:10.297
2 C 0 2018-02-19 23:32:40.700
3 B 1 2018-02-19 23:32:30.247
4 A 1 2018-02-19 23:31:37.153
5 B 0 2018-02-19 23:25:08.667
...
I need to find total number of each score and valid in each month
I mean final result should be like
Month A B C D E Valid(1) NotValid(0)
January 123 343 1021 98 12 1287 480
February 516 421 321 441 421 987 672
...
This is what I tried;
SELECT DATEPART(year, CreatedDate) as Ay,
(select count(*) from TableResults where Score='A') as 'A',
(select count(*) from TableResults where Score='B') as 'B',
...
FROM TableResults
group by DATEPART(MONTH, CreatedDate)
but couldn't figure how to calculate all occurrence of scores on each month.
Use conditional aggregation.
SELECT DATEPART(year, CreatedDate) as YR
, DATEPART(month, CreatedDate) MO
, sum(Case when score = 'A' then 1 else 0 end) as A
, sum(Case when score = 'B' then 1 else 0 end) as B
, sum(Case when score = 'C' then 1 else 0 end) as C
, sum(Case when score = 'D' then 1 else 0 end) as D
, sum(Case when score = 'E' then 1 else 0 end) as E
, sum(case when valid = 1 then 1 else 0 end) as Valid
, sum(case when valid = 0 then 1 else 0 end) as NotValid
FROM TableResults
GROUP BY DATEPART(MONTH, CreatedDate), DATEPART(year, CreatedDate)
I'm not a big fan of queries in the select; I find they tend to cause performance problems in the long run. Since we're aggregating here I just applied the conditional logic to all the columns.

Split SQL column values and group by date and return single row

I have SQL Server query , using this , I am splitting event id sum columns to two columns based on some condition. Query executed successfully, but the result is not desired. It's half useful. Please help me to get expected result. I want one row for both split columns instead two rows and empty spaces.
SQL Query:
select convert(date, paymenttime)) , SUM(case when eventid = 33 then 1 ELSE 0 END) AS column1,
SUM(case when eventid = 36 then 1 ELSE 0 END) AS column2
from tbltransMain_backup where
paymentime <= '20160731' and PaymentTime >= '20160701'
group by convert(date,paymenttime),event_id
order by convert(date,paymenttime)
Result view:
Expected Result:
2016-07-01 27 1
2016-07-02 28 2
2016-07-03 30 15
The query you posted (perhaps unknowingly) into your question should already give you the desired results:
SELECT CONVERT(DATE, paymenttime),
SUM(CASE WHEN event_id = 33 THEN 1 ELSE 0 END) AS column1,
SUM(CASE WHEN event_id = 36 THEN 1 ELSE 0 END) AS column2
FROM tbltransMain_backup
WHERE paymentime <= '20160731' AND
paymentime >= '20160701'
GROUP BY CONVERT(DATE, paymenttime)
ORDER BY CONVERT(DATE, paymenttime)
The reason you were getting two rows for every date is that your query had the following grouping:
GROUP BY CONVERT(DATE, paymenttime),
event_id
In other words, each date would have two groups, one for event_id = 33 and one for event_id = 36.