SQL/PL Rows to Columns using max query with Sub-query - sql

I was using max function to convert from rows to column and before using it in sub-query, it works well.
Situation: [Please refer to the picture as hyperlinked] I have a total of three questions for customer to answer and their responses will be extracted from the database. However, for the first question, customer is allowed to choose from 1 - 10. 10 refers to free text and will be stored in answer for Question = 2.
However, I would like to exclude free text input from the customer and for the extraction to be in column. Having to say that I will be having three columns: Response_1, Response_2 and Response_3. When customer choose 10 for Question = 1, the answer for Question = 3 will be stored in Response_2 while answer for Question = 4 in Response_3.
My attempt is as follow:
select customer_ID
max( CASE WHEN Question = 1 THEN Answer END) Response_1,
max( CASE WHEN Question = 1 AND Answer != 10 THEN
( select
max( CASE WHEN Question = 2 THEN Answer END)
from t_question_answer)
ELSE
( select
max( CASE WHEN Question = 3 THEN Answer END)
from t_question_answer)
END)
) Response_2
from t_question_answer
group by customer_ID
The result went wrong when it comes to the data extracted for customer_2 where I think in the sub-query, it looks for the maximum value in the whole data again instead of specifying the same customer.

You need more conditional logic in your conditional aggregation:
select customer_ID
max(CASE WHEN Question = 1 THEN Answer END) Response_1,
(case when max(case when question = 1 and answer = 10 then 1 else 0 end) > 0
then max( CASE WHEN Question = 3 THEN Answer END)
else max( CASE WHEN Question = 2 THEN Answer END)
end) as Response_2,
(case when max(case when question = 1 and answer = 10 then 1 else 0 end) > 0
then max( CASE WHEN Question = 4 THEN Answer END)
else max( CASE WHEN Question = 3 THEN Answer END)
end) as Response_3
from t_question_answer
group by customer_ID

Related

How to get output in sql two rates into two column in same table

Please help on this. Sometimes my title maybe wrong. Actually i'm unable to explain the problem in word. See below images. Image 1 is db table structure. Image 2 is what I expect result.
I used mentioned query and got result as below image. Also I need to remove 'NULL's and same URGENT_LEVEL values in one row. How i do that? Using ms-sql server.
select TRACKING_NUMBER,URGENT_LEVEL,
case when FROM_KM = '0' then Charge end as 'Under1km' ,
case when FROM_KM='1' then Charge end as '1-100KM'
from my_table
where TRACKING_NUMBER = 'TEST001'
After query
You can use conditional aggregation:
select tracking_number, urgent_level,
sum(case when to_km - from_km <= 1 then charge else 0 end) as charge_under_1,
sum(case when to_km - from_km > 1 and to_km - from_km <= 100 then charge else 0 end) as charge_1_100
from t
group by tracking_number, urgent_level;
I don't know which database you are using, but you need to use group by clause, and something similar to case expression (in oracle) as below :
select TRACKING_NUMBER
, URGENT_LEVEL
, max(case when FROM_KM = 0 and TO_KM = 1 then CHARGE end) as "UNDER 1KM"
, max(case when FROM_KM = 1 and TO_KM = 100 then CHARGE end) as "1-100KM"
from your_table
where TRACKING_NUMBER = 'TEST001'
group by TRACKING_NUMBER, URGENT_LEVEL
order by "UNDER 1KM"
;

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

Combining COUNT Queries [duplicate]

This question already has answers here:
How can I get multiple counts with one SQL query?
(12 answers)
Closed 4 years ago.
I am counting specific things in a SQL Server table. I am using multiple count queries, but I am wondering if it's possible to combine them into a single query with the column name and count numbers in a single table for display.
My queries are:
select count(*) as Ask_Count
from Pld_OpenSalesOrdersLines
where left(C_Item_ID, 1) = '*'
select count(*) as M_Count
from Pld_OpenSalesOrdersLines
where (left(C_Item_ID, 1) = 'M' and len(C_Item_ID) = 1)
select count(*) as MN_Count
from Pld_OpenSalesOrdersLines
where (left(C_Item_ID, 2) = 'MN' and len(C_Item_ID) = 2)
I tried a couple stupid things to combine them, but they were a failure. I honestly can't even begin to think how to combine them, maybe it's not possible?
Thanks!
You could use CASE expression to perform conditional aggregation:
select
COUNT(CASE WHEN LEFT(C_Item_ID,1)='*' THEN 1 END) AS Ask_Count,
COUNT(CASE WHEN LEFT(C_Item_ID,1)='M' AND LEN(C_Item_ID)=1 THEN 1 END) M_Count,
COUNT(CASE WHEN LEFT(C_Item_ID,2)='MN' AND LEN(C_Item_ID)=2 THEN 1 END) MN_Count
from Pld_OpenSalesOrdersLines
Use conditional aggregation:
select sum(case when LEFT(C_Item_ID,1) = '*' then 1 else 0 end) as count_1,
sum(case when LEFT(C_Item_ID,1) = 'M' AND LEN(C_Item_ID)=1 then 1 else 0 end) as count_2,
sum(case when LEFT(C_Item_ID,2) = 'MN' AND LEN(C_Item_ID)=2 then 1 else 0 end) as count_3
from Pld_OpenSalesOrdersLines;
I would write the logic like this, though:
select sum(case when C_Item_ID like '*%' then 1 else 0 end) as count_1,
sum(case when C_Item_ID = 'M' then 1 else 0 end) as count_2,
sum(case when C_Item_ID = 'MN' then 1 else 0 end) as count_3
from Pld_OpenSalesOrdersLines;
Doing a left() on a column and then checking the length is redundant. Just use =.

db2 using CASE with AND inside a SUM

I have multiple lines in a select query on db2 that use CASE with AND inside of a sum function. This worked fine on mySQL but no longer works due to the 'AND'.
Am I not able to use that keyword along with a case statement? I'm trying to aggregate these things as one value a piece and can't find IBM's direct solution to this.
Original query:
select
sum(case when legtype1 = 2 then 1 else 0 end and answered = 1) as total_inbound
, sum(case when legtype1 = 2 then 1 else 0 end and answered = 0) as total_missed
, ROUND(COALESCE(100.00 * sum(case when legtype1 = 2 and answered = 1 then 1 end)/
sum(case when legtype1 = 2 then 1 end), 100),2) as percent_answered
from table1;
I've tried
sum(case when legtype1 = 2 then 1 else 0 end, case when answered = 1 then 1 else 0 end)
But that's not correct either. I need to sum based on both conditions being satisfied, is there a different way I should go about this in DB2? I would think there would be a way to alias each condition but I've yet to find anything.
I think DB/2 is stricter about its conditionals, not letting you AND an int and a conditional, and treat the result as an argument of SUM. Essentially, it's not about AND - you should see the same problem if you try summing Booleans, e.g. SUM(answered = 1)
You should be able to push AND inside the CASE expression, like this:
select
sum(case when legtype1 = 2 and answered = 1 then 1 else 0 end) as total_inbound
, sum(case when legtype1 = 2 and answered = 0 then 1 else 0 end) as total_missed
, ROUND(COALESCE(100.00 * sum(case when legtype1 = 2 and answered = 1 then 1 end)/
sum(case when legtype1 = 2 then 1 end), 100),2) as percent_answered
from table1;
Out of interest, you can sum BOOLEAN values as of Db2 11.1.2.2
drop table table1;
create table table1(legtype1 int, answered int);
insert into table1 values (2,1),(2,1),(null, null),(2,0);
select
sum(legtype1 = 2 and answered = 1) as total_inbound
, sum(legtype1 = 2 and answered = 0) as total_missed
from table1;
TOTAL_INBOUND TOTAL_MISSED
------------- ------------
2 1

best query for a complex situation

I have a table with following columns,(id,fkid, flag1,flag2,flag3,flag4). The possible value for each flag field is -1 to 3 and null is allowed. What I need is a query to check if count of any flag field with value 2 is greater than 3 for a given foreign key fkid. The way I am doing is write a query for each field. It works but very not smart to me. Anyone has better idea? Thanks.
You can do this with one query:
select fkid
from t
group by fkid
having sum(case when flag1 = 2 then 1 else 0 end) > 3 or
sum(case when flag2 = 2 then 1 else 0 end) > 3 or
sum(case when flag3 = 2 then 1 else 0 end) > 3 or
sum(case when flag4 = 2 then 1 else 0 end) > 3
I do agree strongly with the comments, though, that sample data, sample results, and a clear table structure would greatly improve the question.
Query below will also answer your question, sql fiddle example: http://sqlfiddle.com/#!3/adda9/2
SELECT
DISTINCT fkid
FROM
tblTest pvt
UNPIVOT
(
FlagValue FOR Flag IN
(flag1,flag2,flag3,flag4)
) as Unpvt
WHERE
FlagValue = 2
GROUP BY
FKID, FLAG
HAVING COUNT(*)>3