Group by in pivoting in SQL Server 2008 - sql-server-2008

This is just a part my stored procedure comes from a union select
DECLARE #sql AS nvarchar(MAX)
SET #sql = 'SELECT CASE
WHEN [Customer Posting Group] IN (' + '''INHE''' + ',' + '''INH''' + ',' + '''IN HOUSE''' + ') THEN ' + '''IN HOUSE''' + '
WHEN [Customer Posting Group] =' + '''GMA''' + ' AND [COMPANY]=' + '''JLC''' + ' THEN ' + '''JLC GMA''' + '
WHEN [Customer Posting Group] =' + '''GMA''' + ' AND [COMPANY]=' + '''NUDERM''' + ' THEN ' + '''NUDERM GMA''' + '
ELSE [Customer Posting Group]
END AS [Customer Posting Group]
,ISNULL([' + CAST(#PrevYear AS NVARCHAR(10)) + '],0) as [' + CAST(#PrevYear AS NVARCHAR(10)) + ']
,ISNULL([' + CAST(#YEARcurr AS NVARCHAR(10)) + '],0) as [' + CAST(#YEARcurr AS NVARCHAR(10)) + ']
FROM #tmpPERregion
PIVOT(SUM([GROSS AMOUNT])
FOR [MONTH YEAR] IN ([' + CAST(#PrevYear AS NVARCHAR(10)) + '],[' + CAST(#YEARcurr AS NVARCHAR(10)) + '])
) AS PivotSales'
The Result is
Customer Posting Group 2015 2016
JLC GMA 2262533.000000 2181239.500000
IN HOUSE 0.000000 380.000000
IN HOUSE 200.000000 2940.000000
LUZ 241354.000000 265481.500000
MIN 214083.500000 95776.500000
VIS 315547.000000 378649.000000
NUDERM GMA 1588089.000000 1991609.750000
LUZ 574094.000000 717892.250000
MIN 120125.750000 106789.000000
VIS 202294.500000 258561.000000
I want my result to be Group by Customer Posting Group

Try below one, syntactically might be wrong, you need to check for same.
SET #sql = 'Select t.CustomerPostingGroup
,ISNULL([' + CAST(#PrevYear AS NVARCHAR(10)) + '],0) as [' + CAST(#PrevYear AS NVARCHAR(10)) + ']
,ISNULL([' + CAST(#YEARcurr AS NVARCHAR(10)) + '],0) as [' + CAST(#YEARcurr AS NVARCHAR(10)) + ']
From (
Select CASE
WHEN [Customer Posting Group] IN (' + '''INHE''' + ',' + '''INH''' + ',' + '''IN HOUSE''' + ') THEN ' + '''IN HOUSE''' + '
WHEN [Customer Posting Group] =' + '''GMA''' + ' AND [COMPANY]=' + '''JLC''' + ' THEN ' + '''JLC GMA''' + '
WHEN [Customer Posting Group] =' + '''GMA''' + ' AND [COMPANY]=' + '''NUDERM''' + ' THEN ' + '''NUDERM GMA''' + '
ELSE [Customer Posting Group]
END AS CustomerPostingGroup
,Sum([GROSS AMOUNT]) As GROSSAMOUNT
,[MONTH YEAR] As MONTHYEAR
From #tmpPERregion
Where [MONTH YEAR] In (' + #PrevYear + ',' + #YEARcurr + ')
Group By CASE
WHEN [Customer Posting Group] IN (' + '''INHE''' + ',' + '''INH''' + ',' + '''IN HOUSE''' + ') THEN ' + '''IN HOUSE''' + '
WHEN [Customer Posting Group] =' + '''GMA''' + ' AND [COMPANY]=' + '''JLC''' + ' THEN ' + '''JLC GMA''' + '
WHEN [Customer Posting Group] =' + '''GMA''' + ' AND [COMPANY]=' + '''NUDERM''' + ' THEN ' + '''NUDERM GMA''' + '
ELSE [Customer Posting Group]
END
,[MONTH YEAR]
) As t
PIVOT(SUM([GROSSAMOUNT])
FOR [MONTHYEAR] IN ([' + CAST(#PrevYear AS NVARCHAR(10)) + '],[' + CAST(#YEARcurr AS NVARCHAR(10)) + '])
) AS PivotSales'

Related

Using an OnCalcField with a query

// accounts receivable
qAR.SQL.Clear;
qAR.SQL.Text := 'Select C.Lastname,C.Firstname,C.Address,C.City,C.State,C.Zip,' +
'C.Hercell,C.Hiscell,C.Phone,C.Code,' +
'I.Date,I.Clino,I.Date,I.ToBePaid,' +
'SUM(CASE when C.Clino = I.Clino then I.ToBePaid END) as nToBePaid,' +
'SUM(CASE when C.Clino = I.Clino and I.Date between :S0 and :E0 then I.ToBePaid END) as nCurrent,' +
'SUM(CASE when C.Clino = I.Clino and I.Date between :S1 and :E1 then I.ToBePaid END) as nOver30,' +
'SUM(CASE when C.Clino = I.Clino and I.Date between :S2 and :E2 then I.ToBePaid END) as nOver60,' +
'SUM(CASE when C.Clino = I.Clino and I.Date <= :E3 then I.ToBePaid END) as nOver90 ' +
'from Invoice I ' +
'join Client C on C.Clino = I.Clino ' +
'where I.Date <= :E ' +
'and I.ToBePaid <> 0 ' +
'and I.Active = true ' +
'and C.Code <> 1 ' +
'group by C.Clino ' +
'having nToBePaid > 0 ' +
'order by C.Lastname,C.Firstname';
qAR.ParamByName('S0').AsDate := dDate30 + 1;
qAR.ParamByName('E0').AsDate := dBillingDate;
qAR.ParamByName('S1').AsDate := dDate60 + 1;
qAR.ParamByName('E1').AsDate := dDate30;
qAR.ParamByName('S2').AsDate := dDate90 + 1;
qAR.ParamByName('E2').AsDate := dDate60;
qAR.ParamByName('E3').AsDate := dDate90;
qAR.ParamByName('E').AsDate := dBillingDate;
qAR.FieldDefs.Updated := false;
qAR.FieldDefs.Update;
oField := TBooleanField.Create( qAR );
oField.FieldKind := fkCalculated;
qAR.OnCalcFields := qARCalcFields;
qAR.DetailFields := 'Clino';
qAR.Open;
I have a calculated field Sel (boolean) define in this query. I want to click a button and have the Sel fields on all records to be set to TRUE and another button and have them all set to FALSE. What should the code of 1) the OnCalcField and 2) each of the buttons be?
Thanks,
Jim Sawyer

Count value and group by type and date

i have this table
(date format : dd/mm/yyyy)
+ order_id + buyer + date + status +
+----------+-------+------------+-------------+
+ CSR001 + AAA + 01/01/2020 + delivered +
+ CSR002 + AAA + 03/01/2020 + canceled +
+ CSR003 + BBB + 01/01/2020 + delivered +
+ CSR004 + BBB + 04/01/2020 + delivered +
+ CSR005 + AAA + 01/02/2020 + canceled +
+ CSR006 + BBB + 01/02/2020 + delivered +
+ CSR007 + AAA + 01/02/2020 + delivered +
+ CSR008 + AAA + 01/02/2020 + delivered +
+----------+-------+------------+-------------+
what is the query to create view in mysql and make it like this, (Group By buyer, status, and count how many of delivered/cancelled value every month)
+ buyer + status + january + february +
+----------+-----------+-----------+------------+
+ AAA + delivered + 1 + 2 +
+ AAA + cancelled + 1 + 1 +
+ BBB + delivered + 2 + 0 +
+ BBB + cancelled + 0 + 0 +
+----------+-----------+-----------+------------+
You can have condition inside count to differentiate the month:
SELECT t.buyer,
t.status,
COUNT(IF(MONTH(t.date) = 1, 1, NULL)) AS jan,
COUNT(IF(MONTH(t.date) = 2, 1, NULL)) AS feb
FROM TABLE AS t
GROUP BY buyer,
status;

mysql average of best three

I have pieced this together from sites online and it works but not completely, what i need it to do is take the top 3 results and average them but it takes ALL results, can anyone point me in the right direction?
SELECT i.NAME,
e.comp,
Round(Avg(c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6), 2) AS "Average Score",
( CASE
WHEN compID = '7' THEN Concat(Round(Avg(
( (
c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6 ) / 400 ) * 100), 2), ' %')
WHEN compID = '5' THEN Concat(Round(Avg(
( (
c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6 ) / 600 ) * 100), 2), ' %')
WHEN compID = '3' THEN
Concat(Round(Avg(( ( c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6 ) / 600 ) * 100), 2), ' %')
ELSE 'Unspecified'
END ) AS "Average as Percent"
FROM jos_practicedetail c,
jos_comps e,
jos_practice g,
jos_members i
WHERE e.compsid = g.competition
AND g.practiceid = c.practicepid
AND i.memberid = c.competitorid
AND g.typeID = '2'
AND Year(g.pdate) = '2017'
AND (SELECT Count(*)
FROM jos_practicedetail b
WHERE b.competitorid = c.competitorid
AND b.practicepid = c.practicepid
AND ( b.phase1 + b.phase2 + b.phase3 + b.phase4 + b.phase5
+ b.phase6 ) >= (
c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6 )) <= 3
GROUP BY competitorid
HAVING Count(*) > 2
ORDER BY competitorid,
( Avg(c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5
+ c.phase6) ) DESC

MySQL - How to use Left and Right Joins to get the result

I know the values for aw_id, ad_id and grp_id (e.g., aw_id = 5, ad_id = 46 and grp_id =2).
I want to display all the at_cub_details where:
at_cub_details.grp_id = 2 AND
at_cub_details.cd_id = at_cub_awards.cd_id AND
at_cub_awards.aw_id = 5 AND
at_cub_awards.ca_awarded_date IS NULL
OR at_cub_details.cd_id = at_cub_awards.cd_id AND
at_cub_awards.aw_id = 5 does not exist
Where at_cub_details.cd_id = at_cub_awards.cd_id AND
at_cub_awards.aw_id = 5 AND
at_cub_awards.ca_awarded_date = NULL does exist **then**
at_cub_awards.ca_id = at_cub_award_date.ca_id
AND at_cub_award_date.ad_id = 46
AND at_cub_award_date.cad_task_completion_date IS NULL OR
at_cub_awards.ca_id = at_cub_award_date.ca_id AND
at_cub_award_date.ad_id = 46 does not exist
I have have tried all manner of RIGHT and LEFT joins on this without any luck.
The solution was:
String selectQry = ("SELECT * from ( " +
"SELECT DISTINCT at_cub_details.cd_id as cdid, " +
"at_cub_details.grp_id as grpid, " +
"at_cub_details.cd_surname as surname, " +
"at_cub_details.cd_first_name as firstName, " +
"at_cub_details.cd_dob as dob, " +
"at_cub_details.cd_photograph as photograph, " +
"at_cub_details.cd_archived as archived, " +
"at_cub_details.cd_scout_no as scoutNo " +
"FROM at_account_group, at_cub_details " +
"LEFT JOIN at_cub_awards ON (at_cub_details.cd_id = at_cub_awards.cd_id AND at_cub_awards.aw_id = ?) " +
"WHERE at_cub_awards.cd_id IS NULL " +
"AND at_cub_details.grp_id = at_account_group.grp_id " +
"AND at_account_group.acc_id = ? " +
"UNION " +
"SELECT DISTINCT at_cub_details.cd_id as cdid, " +
"at_cub_details.grp_id as grpid, " +
"at_cub_details.cd_surname as surname, " +
"at_cub_details.cd_first_name as firstName, " +
"at_cub_details.cd_dob as dob, " +
"at_cub_details.cd_photograph as photograph, " +
"at_cub_details.cd_archived as archived, " +
"at_cub_details.cd_scout_no as scoutNo " +
"FROM at_account_group, at_cub_details, at_cub_awards, at_cub_award_date " +
"WHERE at_cub_details.grp_id = at_account_group.grp_id " +
"AND at_account_group.acc_id = ? " +
"AND at_cub_awards.cd_id = at_cub_details.cd_id " +
"AND (at_cub_awards.aw_id = ? AND at_cub_awards.ca_awarded_date IS NULL) " +
"AND (at_cub_awards.ca_id = at_cub_award_date. ca_id " +
"AND at_cub_award_date.cad_task_completion_date IS NULL " +
"AND at_cub_award_date.ad_id = ?) " +
"UNION " +
"SELECT DISTINCT at_cub_details.cd_id as cdid, " +
"at_cub_details.grp_id as grpid, " +
"at_cub_details.cd_surname as surname, " +
"at_cub_details.cd_first_name as firstName, " +
"at_cub_details.cd_dob as dob, " +
"at_cub_details.cd_photograph as photograph, " +
"at_cub_details.cd_archived as archived, " +
"at_cub_details.cd_scout_no as scoutNo " +
"FROM at_account_group, at_cub_details, at_cub_awards " +
"LEFT JOIN at_cub_award_date ON (at_cub_awards.ca_id = at_cub_award_date.ca_id) " +
"WHERE at_cub_award_date.ca_id IS NULL " +
"AND at_cub_awards.ca_awarded_date IS NULL AND at_cub_awards.aw_id = ? " +
"AND at_cub_details.grp_id = at_account_group.grp_id " +
"AND at_account_group.acc_id = ? " +
"AND at_cub_awards.cd_id = at_cub_details.cd_id " +
" ) a " +
"ORDER BY surname, firstName;");

MySQL query inc AVG

after a bit of help please :)
The following MySQL query
select id, customer_id, user,
(((q_responce_time + o_responce_time + cs_responce_time + q_accuracy +
o_accuracy + cs_accuracy + q_personnel + o_personnel + cs_personnel +
q_communication + o_communication + d_communication + cs_communication +
q_overall + qu_overall + o_overall + d_overall + cs_overall + profile +
glass + parts + roof + in_full + direct_delivery + damages + service)/125)*100) as total,
month(create_datetime) as posted_month
from cs_review_centre
Where
create_datetime >= '2013-01-01'
and create_datetime < '2013-10-31'
and customer_id = 26
order by posted_month, customer_id
produces the following result
"customer_id" | "user" |"total" |"posted_month"|
"26" | "co2_test" |"72.8000" | "7" |
"26" | "co2_test" |"60.8000" | "8" |
"26" | "Lisa" |"81.6000" | "9" |
"26" | "Lisa" |"84.0000" | "10" |
"26" | "Lisa" |"52.0000" | "10" |
what I want to achieve is when a posted_month contains a duplicate value I want to average the "total"
Any help would very greatly appreciated
Thanks
Just GROUP BY customer_id, user,posted_month and use AVG() function
select customer_id, user,
AVG(
(((q_responce_time + o_responce_time + cs_responce_time + q_accuracy +
o_accuracy + cs_accuracy + q_personnel + o_personnel + cs_personnel +
q_communication + o_communication + d_communication + cs_communication +
q_overall + qu_overall + o_overall + d_overall + cs_overall + profile +
glass + parts + roof + in_full + direct_delivery + damages + service)/125)*100)
) as AverageTotal,
month(create_datetime) as posted_month
from cs_review_centre
Where
create_datetime >= '2013-01-01'
and create_datetime < '2013-10-31'
and customer_id = 26
GROUP BY customer_id, user,posted_month
order by posted_month, customer_id
Try:
select id, customer_id, user,
avg((((q_responce_time + o_responce_time + cs_responce_time + q_accuracy +
o_accuracy + cs_accuracy + q_personnel + o_personnel + cs_personnel +
q_communication + o_communication + d_communication + cs_communication +
q_overall + qu_overall + o_overall + d_overall + cs_overall + profile +
glass + parts + roof + in_full + direct_delivery + damages + service)/125)*100)) as total,
month(create_datetime) as posted_month
from cs_review_centre
Where
create_datetime >= '2013-01-01'
and create_datetime < '2013-10-31'
and customer_id = 26
group by id, customer_id, user, month(create_datetime)
order by posted_month, customer_id