Combining multiple rows in a single row - sql

I have SQL Query like this in SSMS
select distinct (b.TransactionNumber),
(case when b.Amount > 0 then c.total else 0 end) as 'Total Sales',
(case when b.TenderID = 1 then b.Amount else 0 end) as 'Cash',
(case when b.TenderID = 20 then b.Amount else 0 end) as 'Gift Certificates'
from [Transaction] c
inner join TenderEntry b on c.TransactionNumber = b.TransactionNumber
but the output is(see image for reference)
This should be the expected output(see image for reference)

I would expect one row per transaction number, especially given your use of select distinct:
select t.TransactionNumber, te.total as total_sales,
sum(case when t.TenderID = 1 then t.Amount else 0 end) as Cash,
sum(case when t.TenderID = 20 then t.Amount else 0 end) as Gift_Certificates
from TenderEntry te join
Transaction t
on te.TransactionNumber = t.TransactionNumber
group by t.TransactionNumber, te.total;
This produces one row per transaction.
Note the changes to the query:
The table aliases are meaningful (i.e. abbreviations of table names) rather than arbitrary letters.
The column aliases do not use single quotes. Only use single quotes for string and date constants.
The column aliases have been simplified so they do not need to be escaped.
It occurs to me that you might want to "list" the cash and gifts in the two columns. This would look like:
select TransactionNumber,
max(case when seqnum = 1 then total end) as total_sales,
sum(case when tenderId = 1 then amount end) as cash,
sum(case when tenderId = 20 then amount end) as Gift_Certificates
from (select t.TransactionNumber, te.total, t.amount, t.TenderID,
row_number() over (partition by t.TransactionNumber, t.TenderId order by t.amount) as seqnum
from TenderEntry te join
Transaction t
on te.TransactionNumber = t.TransactionNumber
where tenderid in (1, 20)
) x
group by t.TransactionNumber, seqnum;

This is only a partial answer, but I put it here because I cannot fit it into comments well enough.
It is likely that you do not want the DISTINCT component in the select. SELECT DISTINCT find all unique rows. So if you have 3 rows which all have some differences, it will show all three. If, on the other hand, there were two rows the same (e.g., they paid for a $100 item with two $50 vouchers) it would just ignore one of them.
Instead, you probably need to become familiar with 'GROUP BY' which allows you to find totals etc across multiple rows.
For example (although not tested)
select
(b.TransactionNumber),
(case when b.Amount > 0 then c.total else 0 end) as 'Total Sales',
SUM(case when b.TenderID = 1 then b.Amount else 0 end) as 'Cash',
SUM(case when b.TenderID = 20 then b.Amount else 0 end) as 'Gift Certificates'
from [Transaction] c
inner join TenderEntry b on c.TransactionNumber = b.TransactionNumber
GROUP BY (b.TransactionNumber, (case when b.Amount > 0 then c.total else 0 end))
In the above, I have removed the DISTINCT, added 'SUM' for the two transaction values (cash/certificates) and the GROUP BY across the TransactionNumber and Total sales (as that seems to be common across the transaction).
For the above data, what that would produce is 1 line of data for TransactionNumber = 1, with sales = 250 (as all the lines have that), and totals for cash and gift certificates (150 and 100 respectively if my maths is correct).
However, that is not your desired answer, - you want this transaction to go over two lines. Firstly, are you sure of that?
If you do, then we need another criteria by which to group them and you will need to specify that e.g., why does this transaction's report need to go over two lines rather than just one?
Other notes
'Transaction' is a special word within SQL Server. You are allowed to use it, but I would consider renaming the table.

Related

how to consolidate information from various rows in to 1 in SQL Server?

I have a table in SQL Server called [orders]:
I have another table called [order_details]:
as you can see, if the media_type is various in [orders] table, there will be 2 corresponding rows in [order_details].
how can i make the below table?
i was trying the method that the admins suggested even before they closed down my original question but what i was getting was the below:
i need this to be like:
You seem to just want conditional aggregation on order_details:
select od.order_id,
sum(case when od.media_type = 'Loose Cartons' then qty else 0 end) as loose_cartons,
sum(case when od.media_type = 'Loose Units' then qty else 0 end) as loose_units
from order_details od
group by od.order_id;
you would just perform an aggregation on the query that got you these results
select [order id]
,max(pallets) as pallets
,max([total cartons]) as [total cartons]
,max(units) as units
,max(sets) as sets
,max(GOH) as GOH
,max([Loose Cartons]) as [Loose Cartons]
,max([Loose Units]) as [Loose Units]
from (<insert query that got you the results with two records >
)
group by [order id]
ok guys sorted.
So i had to create a separate table with just the order_id and 3 more columns with Pallets, Cartons and Sets.
i had to use "max" not "sum" otherwise it would double the quantity.
so what i used was:
create view SSDView_2ND_VB as
select
a.ORDER_ID
,max(case when b.MEDIATYPE_ID = '1' then b.ORDER_DETAIL_QUANTITY else null end) as [Pallets]
,max(case when b.MEDIATYPE_ID = '2' then b.ORDER_DETAIL_QUANTITY else null end) as [Cartons]
,max(case when b.MEDIATYPE_ID = '3' then b.ORDER_DETAIL_QUANTITY else null end) as [Sets]
from
SSDView_1ST_VB as a
left join ORDER_DETAIL as b
on a.ORDER_ID = b.ORDER_ID
group by a.ORDER_ID
The SSDView_1ST_VB was just another view which only had media type 'VARIOUS'.
I would like to thank you all for your help, really appreciate it guys ^^

total and group multiple column values in a single query

I am looking to get a summary of multiple states from the same column.
select c.brand
sum amount as total
from charges as c
where c.invoive_id is not null
and c.paid = true
group by c.brand
gets me the sum of all completed purchases grouped by brand.
I want to have a separate column in the same query, summed by brand for "c.paid = false"
so I will have:
Brand Total(true) Total(false)
b_one 25 12
b_two 38 16
You seems to have a simple conditional aggregation statement -
SELECT c.brand
,SUM(CASE WHEN c.paid = 'true' THEN amount END) as Total(true)
,SUM(CASE WHEN c.paid = 'false' THEN amount END) as Total(false)
from charges as c
where c.invoive_id is not null
group by c.brand
You don't say which database you are using so I'll assume PostgreSQL. You can usually use a CASE clause to do this. For example:
select
c.brand,
sum(case when c.paid then 1 else 0 end) as total_true,
sum(case when c.paid then 0 else 1 end) as total_false
from charges as c
where c.invoive_id is not null
group by c.brand
In databases that support boolean types, you can often do:
select c.brand,
sum(c.paid) as num_true,
sum(not c.paid) as num_falst
from charges as c
where c.invoive_id is not null
group by c.brand

Sum a column and perform more calculations on the result? [duplicate]

This question already has an answer here:
How to use an Alias in a Calculation for Another Field
(1 answer)
Closed 3 years ago.
In my query below I am counting occurrences in a table based on the Status column. I also want to perform calculations based on the counts I am returning. For example, let's say I want to add 100 to the Snoozed value... how do I do this? Below is what I thought would do it:
SELECT
pu.ID Id, pu.Name Name,
COUNT(*) LeadCount,
SUM(CASE WHEN Status = 'Working' THEN 1 ELSE 0 END) AS Working,
SUM(CASE WHEN Status = 'Uninterested' THEN 1 ELSE 0 END) AS Uninterested,
SUM(CASE WHEN Status = 'Converted' THEN 1 ELSE 0 END) AS Converted,
SUM(CASE WHEN SnoozedId > 0 THEN 1 ELSE 0 END) AS Snoozed,
Snoozed + 100 AS Test
FROM
Prospects p
INNER JOIN
ProspectsUsers pu on p.OwnerId = pu.SalesForceId
WHERE
p.Store = '108'
GROUP BY
pu.Name, pu.Id
ORDER BY
Name
I get this error:
Invalid column name 'Snoozed'.
How can I take the value of the previous SUM statement, add 100 to it, and return it as another column? What I was aiming for is an additional column labeled Test that has the Snooze count + 100.
You can't use one column to create another column in the same way that you are attempting. You have 2 options:
Do the full calculation (as #forpas has mentioned in the comments above)
Use a temp table or table variable to store the data, this way you can get the first 5 columns, and then you can add the last column or you can select from the temp table and do the last column calculations from there.
You can not use an alias as a column reference in the same query. The correct script is:
SELECT
pu.ID Id, pu.Name Name,
COUNT(*) LeadCount,
SUM(CASE WHEN Status = 'Working' THEN 1 ELSE 0 END) AS Working,
SUM(CASE WHEN Status = 'Uninterested' THEN 1 ELSE 0 END) AS Uninterested,
SUM(CASE WHEN Status = 'Converted' THEN 1 ELSE 0 END) AS Converted,
SUM(CASE WHEN SnoozedId > 0 THEN 1 ELSE 0 END)+100 AS Snoozed
FROM
Prospects p
INNER JOIN
ProspectsUsers pu on p.OwnerId = pu.SalesForceId
WHERE
p.Store = '108'
GROUP BY
pu.Name, pu.Id
ORDER BY
Name
MSSQL does not allow you to reference fields (or aliases) in the SELECT statement from within the same SELECT statement.
To work around this:
Use a CTE. Define the columns you want to select from in the CTE, and then select from them outside the CTE.
;WITH OurCte AS (
SELECT
5 + 5 - 3 AS OurInitialValue
)
SELECT
OurInitialValue / 2 AS OurFinalValue
FROM OurCte
Use a temp table. This is very similar in functionality to using a CTE, however, it does have different performance implications.
SELECT
5 + 5 - 3 AS OurInitialValue
INTO #OurTempTable
SELECT
OurInitialValue / 2 AS OurFinalValue
FROM #OurTempTable
Use a subquery. This tends to be more difficult to read than the above. I'm not certain what the advantage is to this - maybe someone in the comments can enlighten me.
SELECT
5 + 5 - 3 AS OurInitialValue
FROM (
SELECT
OurInitialValue / 2 AS OurFinalValue
) OurSubquery
Embed your calculations. opinion warning This is really sloppy, and not a great approach as you end up having to duplicate code, and can easily throw columns out-of-sync if you update the calculation in one location and not the other.
SELECT
5 + 5 - 3 AS OurInitialValue
, (5 + 5 - 3) / 2 AS OurFinalValue
You can't use a column alias in the same select. The column alias do not precedence / sequence; they are all created after the eval of the select result, just before group by and order by.
You must repeat code :
SELECT
pu.ID Id,pu.Name Name,
COUNT(*) LeadCount,
SUM(CASE WHEN Status = 'Working' THEN 1 ELSE 0 END) AS Working,
SUM(CASE WHEN Status = 'Uninterested' THEN 1 ELSE 0 END) AS Uninterested,
SUM(CASE WHEN Status = 'Converted' THEN 1 ELSE 0 END) AS Converted,
SUM(CASE WHEN SnoozedId > 0 THEN 1 ELSE 0 END) AS Snoozed,
SUM(CASE WHEN SnoozedId > 0 THEN 1 ELSE 0 END)+ 100 AS Test
FROM
Prospects p
INNER JOIN
ProspectsUsers pu on p.OwnerId = pu.SalesForceId
WHERE
p.Store = '108'
GROUP BY
pu.Name, pu.Id
ORDER BY
Name
If you don't want to repeat the code, use a subquery
SELECT
ID, Name, LeadCount, Working, Uninterested,Converted, Snoozed, Snoozed +100 AS test
FROM
(SELECT
pu.ID Id,pu.Name Name,
COUNT(*) LeadCount,
SUM(CASE WHEN Status = 'Working' THEN 1 ELSE 0 END) AS Working,
SUM(CASE WHEN Status = 'Uninterested' THEN 1 ELSE 0 END) AS Uninterested,
SUM(CASE WHEN Status = 'Converted' THEN 1 ELSE 0 END) AS Converted,
SUM(CASE WHEN SnoozedId > 0 THEN 1 ELSE 0 END) AS Snoozed
FROM Prospects p
INNER JOIN ProspectsUsers pu on p.OwnerId = pu.SalesForceId
WHERE p.Store = '108'
GROUP BY pu.Name, pu.Id) t
ORDER BY Name
or a view

Change sub query to join

all I have used subquery[Below] to identify the percentage. But I need a query without subquery. Can anyone please help me, how to use joins to calculate the percentage?
Query used
SELECT 'Dropping_Percentage',
( Cast(dropped_count AS DECIMAL(16, 9)) / Cast(new_count AS DECIMAL(16, 9
)) ) *
100
FROM (SELECT count AS New_count,
'1' a
FROM new_count)a,
(SELECT Count(*) Dropped_count,
'1' b
FROM pfo_bhi_new N
RIGHT JOIN pfo_bhi_old o
ON o.id_membid_claimid_c = N.id_membid_claimid_c
WHERE N.id_membid_claimid_c IS NULL)c
WHERE a.a = c.b
"I need a query without subquery."
Answer:
SELECT Count(*) All_count
, SUM(CASE WHEN N.id_membid_claimid_c IS NULL THEN 1 else 0 end) as Dropped_count
, SUM(CASE WHEN N.id_membid_claimid_c IS NULL THEN 1 else 0 end) * 1.0 / Count(*) as Dropping_Percentage
FROM pfo_bhi_new N
RIGHT JOIN pfo_bhi_old o ON o.id_membid_claimid_c = N.id_membid_claimid_c
Explanation:
Reviewing the main query with assumptions about the content:
SELECT Count(*) Dropped_count, '1' b
FROM pfo_bhi_new N
RIGHT JOIN pfo_bhi_old o ON o.id_membid_claimid_c = N.id_membid_claimid_c
WHERE N.id_membid_claimid_c IS NULL
should give you the number of records in pfo_bhi_old that do not appear in pfo_bhi_new. Assumption here is that you need to do the total based on the existing right join. All the matching and non matching records.
Therefore It's possible to count all the existing records by removing the where clause,
COUNT(*) would give you that total.
Next you want to count the ones where there's no match which will give you the "Dropping count" the value you had before with the where clause, that is where ones where the id_membid_claimid_c was null that is SUM(CASE WHEN N.id_membid_claimid_c IS NULL THEN 1 else 0 end). Said differently it will add 1 to the sum only when the id_membid_claimid_c field is null, otherwise it will add zero (0).
I've multiplied the numerator by 1.0 to force SQL Server to use decimal values and make the query easier to read.
Here's what it should look like if you needed to use decimals(16,9) as the result.
SELECT Count(*) All_count
, SUM(CASE WHEN N.id_membid_claimid_c IS NULL THEN 1 else 0 end) as Dropped_count
, SUM(CASE WHEN N.id_membid_claimid_c IS NULL THEN 1 else 0 end) * 1.0 / Count(*) as Dropping_Percentage
, CAST(SUM(CASE WHEN N.id_membid_claimid_c IS NULL THEN 1 else 0 end) AS DECIMAL(16,9)) / CAST(Count(*) AS DECIMAL(16,9)) as Dropping_Pct_16_9
FROM pfo_bhi_new N
RIGHT JOIN pfo_bhi_old o ON o.id_membid_claimid_c = N.id_membid_claimid_c

nested SQL queries on one table

I am having trouble formulating a query to get the desired output.
This query involves one table and two columns.
First column bld_stat has 4 different values Private, public, Public-Abandoned, Private-Abandoned the other column bld_type, single_flr, multi_flr, trailer, Whs.
I need to get results that look like this:
So far I can get the first two columns but after that I have not been able to logically get a query to work
SELECT bld_stat, COUNT(grade) AS single_flr
FROM (SELECT bld_stat,bld_type
FROM bld_inventory WHERE bld_type = 'single_flr') AS grade
GROUP BY bld_stat,bld_type,grade
The term you are going for is pivoting. I think this should work...no need for the subquery, and I've changed your group by to only bld_stat
SELECT bld_stat,
sum(case when bld_type = 'singl_flr' then 1 else 0 end) AS single_flr,
sum(case when bld_type = 'multi_flr' then 1 else 0 end) AS multi_flr,
sum(case when bld_type = 'trailer' then 1 else 0 end) AS trailer,
sum(case when bld_type = 'whs' then 1 else 0 end) AS WHS
FROM bld_inventory
GROUP BY bld_stat