Compare Months list with date field of table - sql-server-2008

I am using sql server 2008
I have table in my database is like this:
And I want output like this:
As it is shown in my table I have DateField which has smalldatetime datatype and along with fruits and vegi fields. I want output like which shows data month-wise.. month comparison should be performed based on DateField of my table.

You can use something like:
select [Month] = month(DateField)
, [MonthName] = left(datename(mm, DateField), 3)
, TotalAmountApple = sum(case when fruits = 'Apple' then 1 else 0 end)
, TotalAmountOnion = sum(case when vegi = 'Onion' then 1 else 0 end)
from produce
group by month(DateField)
, left(datename(mm, DateField), 3)
order by [Month]
Full test details (no SQL Fiddle as it's experiencing issues):
create table produce
(
id int
, fruits varchar(10)
, vegi varchar(10)
, DateField smalldatetime
)
insert into produce
select 1, 'Apple', 'Chilly', '01-jan-2013'
insert into produce
select 1, 'Mango', 'Onion', '15-jan-2013'
insert into produce
select 1, 'Mango', 'Chilly', '20-jan-2013'
insert into produce
select 1, 'Apple', 'Chilly', '01-Feb-2013'
insert into produce
select 1, 'Mango', 'Onion', '15-Feb-2013'
insert into produce
select 1, 'Apple', 'Onion', '20-Feb-2013'
select [Month] = month(DateField)
, [MonthName] = left(datename(mm, DateField), 3)
, TotalAmountApple = sum(case when fruits = 'Apple' then 1 else 0 end)
, TotalAmountOnion = sum(case when vegi = 'Onion' then 1 else 0 end)
from produce
group by month(DateField)
, left(datename(mm, DateField), 3)
order by [Month]

Related

Case in where condition to calculate individual totals

select
Count(*)
from gl
join TRVMAINDATA msit
on gl.TRANSACTIONID = msit.CHARGETRANSACTIONID
where gl.CREATEDDATETIME >= DATEADD(MONTH,-2,getdate()) AND
datediff(DAY,gl.BUSINESSPROCESSDATE,gl.CREATEDDATETIME)>=4 AND
gl.MARKETCODE In('535','532','056','050','039','036','034','033','030','029','027','023','022','021','018','015','012','011','010','009','007','006','005','002','001' ) and DATEADD(MONTH,DATEDIFF(MONTH,0,gl.CREATEDDATETIME),0) = '2/1/2017 12:00:00 AM'
The above code gives the total for market code mentioned.
But i also want the market code for other code which doesn't belog here. for example
select
Count(*)
from gl
join TRVMAINDATA msit
on gl.TRANSACTIONID = msit.CHARGETRANSACTIONID
where gl.CREATEDDATETIME >= DATEADD(MONTH,-6,getdate()) AND
datediff(DAY,gl.BUSINESSPROCESSDATE,gl.CREATEDDATETIME)>=0
and
DATEADD(MONTH,DATEDIFF(MONTH,0,gl.CREATEDDATETIME),0) = '2/1/2017 12:00:00 AM'
AND
(case
when gl.MARKETCODE In('535','532','056','050','039','036','034','033','030','029','027','023','022','021','018','015','012','011','010','009','007','006','005','002','001') then 'Proprietary'
when gl.MARKETCODE='037' then 'US'
else 'partner'
end )
Is it possible to calculate totals of other market codes in one sql query or do i have to calculate individually?
I think you would like to do count with case when in select statement like this:
SELECT COUNT(CASE
WHEN gl.marketcode IN ( '535', '532', '056', '050',
'039', '036', '034', '033',
'030', '029', '027', '023',
'022', '021', '018', '015',
'012', '011', '010', '009',
'007', '006', '005', '002', '001' ) THEN 1
ELSE NULL
END) AS `Proprietary`,
COUNT(CASE
WHEN gl.marketcode = '037' THEN 1
ELSE NULL
END) AS `US`,
COUNT(CASE
WHEN gl.marketcode NOT IN ( '535', '532', '056', '050',
'039', '036', '034', '033',
'030', '029', '027', '023',
'022', '021', '018', '015',
'012', '011', '010', '009',
'007', '006', '005', '002',
'001', '037' ) THEN 1
ELSE NULL
END) AS `partner`
FROM gl
JOIN trvmaindata msit
ON gl.transactionid = msit.chargetransactionid
WHERE gl.createddatetime >= DATEADD(month, -2, GETDATE())
AND DATEDIFF(day, gl.businessprocessdate, gl.createddatetime) >= 4
AND DATEADD(month, DATEDIFF(month, 0, gl.createddatetime), 0) = '2/1/2017 12:00:00 AM'

MySQL - conditional select in group

I have a simple table with several rows and I would like to group them by id_room and select value only when condition is true. Problem is that condition is always false even there is a row with right date column year_month.
Here is schema:
CREATE TABLE tbl_account_room (
`id` int,
`year_month` date,
`value` int,
`id_room` int
);
INSERT INTO tbl_account_room
(`id`, `year_month`, `value`, `id_room`)
VALUES
(1, '2016-08-01', 1, 300),
(2, '2016-09-01', 2, 300),
(3, '2016-10-01', 3, 300);
and here query:
SELECT
(case when '2016-10-01' = ar.year_month then ar.value else 0 end) as total
FROM tbl_account_room AS ar
WHERE ar.year_month >= "2016-08-01"
AND ar.year_month <= "2016-11-01"
and ar.id_room = '300'
GROUP BY ar.id_room
LIMIT 10
Here is SQL Fiddle
In column total I'm getting 0 and I would like to get value 3 because year_month is 2016-10-01. Why this happens?
You certainly don't need that CASE condition and include that condition in your WHERE clause rather like
SELECT
ar.value as total,
GROUP_CONCAT(ar.year_month)
FROM tbl_account_room AS ar
WHERE ar.year_month = '2016-10-01'
GROUP BY ar.id_room;
Not sure why you want the result like that, here you can use self join to do that:
SELECT
MAX(t1.value) as total,
GROUP_CONCAT(ar.year_month)
FROM tbl_account_room AS ar
LEFT JOIN tbl_account_room AS t1
ON ar.id_room = t1.id_room
AND ar.year_month = t1.year_month
AND t1.year_month = '2016-10-01'
WHERE ar.year_month >= "2016-08-01"
AND ar.year_month <= "2016-11-01"
and ar.id_room = '300'
GROUP BY ar.id_room
LIMIT 10;
and here is SQLFiddle Demo.

MySQL - Rows to Columns and keeps NULL

We have the following table (TEST2) in the MySQL database (MySQL 5.6):
TEAM_ID,MEMBER_ID,TYPE,SCORE
1,2,A,150
1,3,B,200
1,1,B,50
1,1,A,100
1,2,B,NULL
We try to transform/pivot the above table based on the TYPE column:
If the TYPE column has value == A, move the value in the SCORE column into a new column called A_SCORE. If the value in the SCORE column is NULL, it should show NULL in the new A_SCORE column.
If the TYPE column has value == B, move the value in the SCORE column into a new column called B_SCORE. If the value in the SCORE column is NULL, it should show NULL in the new B_SCORE column.
The following table is the one we are looking for (the wanted table):
TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE,A_SCORE_MINUS_B_SCORE
1,1,100,50,50
1,2,150,NULL,NULL
1,3,0,200,-200
We tried the following query
SELECT TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE,SUM(A_SCORE-B_SCORE) AS ACTUAL_MINUS_B_SCORE FROM
(SELECT TEAM_ID,MEMBER_ID,
CASE
WHEN SCORE IS NULL
THEN NULL
ELSE SUM(if(TYPE = 'A', SCORE,0) )
END A_SCORE,
CASE
WHEN SCORE IS NULL
THEN NULL
ELSE SUM(if(TYPE = 'B', SCORE,0) )
END B_SCORE
FROM TEST2
GROUP BY TEAM_ID,MEMBER_ID,SCORE) AS A
GROUP BY TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE);
It returns something we don’t want:
TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE,A_SCORE_MINUS_B_SCORE
1,1,0,50,-50
1,1,100,0,100
1,2,0,0,0
1,2,150,0,150
1,3,0,200,-200
If we tried the following, it generates a table close to what we want, but it doesn’t return any NULL value.
SELECT TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE,SUM(A_SCORE-B_SCORE) AS A_SCORE _MINUS_B_SCORE FROM
(SELECT TEAM_ID,MEMBER_ID,
SUM(if(TYPE = 'A', SCORE,0) ) AS A_SCORE,
SUM(if(TYPE = 'B', SCORE,0) )AS B_SCORE
FROM TEST2
GROUP BY TEAM_ID,MEMBER_ID) AS A
GROUP BY TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE;
The result of the above query:
TEAM_ID,MEMBER_ID,A_SCORE,B_SCORE,A_SCORE_MINUS_B_SCORE
1,1,100,50,50
1,2,150,0,0
1,3,0,200,-200
Could any guru enlighten how to generate the wanted table in this case using MySQL? The SQL fiddle is here for your convenience.
http://sqlfiddle.com/#!9/cfe7a1/1
Thanks!
Try this;)
SELECT TEAM_ID, MEMBER_ID, A_SCORE, B_SCORE, A_SCORE - B_SCORE AS A_SCORE_MINUS_B_SCORE
FROM (
SELECT
TEAM_ID, MEMBER_ID,
CASE
WHEN A_SCORE IS NULL AND NOT EXISTS (
SELECT 1 FROM TEST2
WHERE TEAM_ID = T1.TEAM_ID
AND MEMBER_ID = T1.MEMBER_ID
AND TYPE = 'A'
) THEN 0 ELSE A_SCORE END AS A_SCORE,
CASE
WHEN B_SCORE IS NULL AND NOT EXISTS (
SELECT 1 FROM TEST2
WHERE TEAM_ID = T1.TEAM_ID
AND MEMBER_ID = T1.MEMBER_ID
AND TYPE = 'A'
) THEN 0 ELSE B_SCORE END AS B_SCORE
FROM (
SELECT
TEAM_ID, MEMBER_ID,
MAX(CASE WHEN TYPE = 'A' THEN SCORE END) AS A_SCORE,
MAX(CASE WHEN TYPE = 'B' THEN SCORE END) AS B_SCORE
FROM TEST2
GROUP BY TEAM_ID, MEMBER_ID
) T1
)T
SQLFiddle demo here
I don't quite understand the calculation criteria, but something like this should work...
SELECT team_id
, member_id
, COALESCE(MAX(CASE WHEN type = 'A' THEN score END),0) a_score
, COALESCE(MAX(CASE WHEN type = 'B' THEN score END),0) b_score
, COALESCE(MAX(CASE WHEN type = 'A' THEN score END),0)
- COALESCE(MAX(CASE WHEN type = 'B' THEN score END),0) diff
FROM test2
GROUP
BY team_id
, member_id;

Subquery SUM with different date

I retrieve two sum of value:
SUM (CASE WHEN CAUSALI.AVAILABLECAUSA_1 LIKE ('%CAUSE-1%') THEN (mtscrap) ELSE 0 END ) as Cause1
and
SUM (CASE WHEN CAUSALI.AVAILABLECAUSA_1 LIKE ('%CAUSE-2%') THEN (mtscrap) ELSE 0 END ) as Cause2
I would like to set another SUM statement without %CAUSE-*, and that have WHERE clause independent from the principal WHERE. I had innested this subquery:
(CASE WHEN day BETWEEN '2014-01-09' AND '2014-06-13' THEN SUM(MTSCRAP) ELSE 0 END) AS XXXXXX
but I have wrong data. My global query is:
SELECT
SezioneID
, Desc_Prod
, sample.products.VETTURA AS VetturaID
, truncate((SUM(mtscrap_1) / SUM(MtProdotti_1)) * 100, 2) AS Scrap_1
, truncate((SUM(mtscrap_2) / SUM(MtProdotti_2)) * 100, 2) AS Scrap_2
, mtscrap_1
, MtProdotti_1
, mtscrap_2
, MtProdotti_2
FROM flB.flB_prod AS PROD
JOIN SAMPLE.PRODUCTS
ON (sample.products.SKU = PROD.SEZIONEID)
AND (sample.products.LINEA = 'FLB')
JOIN (
SELECT
IDSEZIONE
, IDTURNO
, ID_PROG
, SUM(CASE
WHEN AVAILABLECAUSA_1 LIKE ('%CHANGE-1%') THEN mtscrap ELSE 0
END) AS mtscrap_1
, SUM(CASE
WHEN AVAILABLECAUSA_1 LIKE ('%CHANGE-1%') THEN MtProdotti ELSE 0
END) AS MtProdotti_1
, SUM(CASE
WHEN AVAILABLECAUSA_1 LIKE ('%CHANGE-2%') THEN mtscrap ELSE 0
END) AS mtscrap_2
, SUM(CASE
WHEN AVAILABLECAUSA_1 LIKE ('%CHANGE-2%') THEN MtProdotti ELSE 0
END) AS MtProdotti_2
, MtProdotti
FROM FLB.flB_causali
WHERE DATASTARTPRG BETWEEN '2014-06-09' AND '2014-06-13'
GROUP BY
IDSEZIONE
IDTURNO
, ID_PROG
) AS CAUSALI
ON (PROD.SEZIONEID = CAUSALI.IDSEZIONE)
AND PROD.TURNO = CAUSALI.IDTURNO
AND PROD.ID_PROG = CAUSALI.ID_PROG
WHERE giorno BETWEEN '2014-06-09' AND '2014-06-13'
GROUP BY
SezioneID
I need this view:
I have done my best to put a table or alias beside EVERY field reference. At this point I really do not know what else I can do for you. I don't think any more words will help.
these 2 simple items will help:
1. sample data
2. expected result
Because you did not use table aliases on all fields in the very original query the following is a complete guess, but using the presence of DISTINCT in that original query was a clue for "too many rows" that indicated the need for grouping prior to the overall query. So, here's my first guess:
SELECT
PROD.SezioneID
, PROD.Desc_Prod
, sample.products.VETTURA AS VetturaID
, truncate((SUM(CAUSALI.mtscrap_1) / SUM(CAUSALI.MtProdotti_1)) * 100, 2) AS Scrap_1
, truncate((SUM(CAUSALI.mtscrap_2) / SUM(CAUSALI.MtProdotti_2)) * 100, 2) AS Scrap_2
, CAUSALI.mtscrap_1
, CAUSALI.MtProdotti_1
, CAUSALI.mtscrap_2
, CAUSALI.MtProdotti_2
FROM flB.flB_prod AS PROD
JOIN SAMPLE.PRODUCTS
ON (sample.products.SKU = PROD.SEZIONEID)
AND (sample.products.LINEA = 'FLB')
JOIN (
SELECT
flB_causali.IDSEZIONE
, flB_causali.IDTURNO
, flB_causali.ID_PROG
, SUM(CASE
WHEN flB_causali.AVAILABLECAUSA_1 LIKE ('%CHANGE-1%') THEN flB_causali.mtscrap ELSE 0
END) AS mtscrap_1
, SUM(CASE
WHEN flB_causali.AVAILABLECAUSA_1 LIKE ('%CHANGE-1%') THEN flB_causali.MtProdotti ELSE 0
END) AS MtProdotti_1
, SUM(CASE
WHEN flB_causali.AVAILABLECAUSA_1 LIKE ('%CHANGE-2%') THEN flB_causali.mtscrap ELSE 0
END) AS mtscrap_2
, SUM(CASE
WHEN flB_causali.AVAILABLECAUSA_1 LIKE ('%CHANGE-2%') THEN flB_causali.MtProdotti ELSE 0
END) AS MtProdotti_2
, flB_causali.MtProdotti
FROM FLB.flB_causali
WHERE flB_causali.DATASTARTPRG BETWEEN '2014-06-09' AND '2014-06-13'
GROUP BY
flB_causali.IDSEZIONE
flB_causali.IDTURNO
, flB_causali.ID_PROG
) AS CAUSALI
ON (PROD.SEZIONEID = CAUSALI.IDSEZIONE)
AND PROD.TURNO = CAUSALI.IDTURNO
AND PROD.ID_PROG = CAUSALI.ID_PROG
WHERE PROD.giorno BETWEEN '2014-06-09' AND '2014-06-13'
GROUP BY
PROD.SezioneID
;
Are you looking for this expression?
SUM(CASE WHEN day BETWEEN '2014-01-09' AND '2014-06-13' THEN MTSCRAP ELSE 0 END) AS XXXXXX
The CASE goes inside the SUM() for conditional aggregation.

sql query that produce the following result

can anyone tell me the sql query(MySQL) that will result following output from the table .
You're after a PIVOT TABLE QUERY - although it's often better to perform the basic aggregation in (My)SQL and then handle problems of display at the application level (e.g. with a bit of PHP).
A standard query might look as follows, although MySQL supports shorthand deviations from this standard...
SELECT DATE_FORMAT(date,'%M') month
, COALESCE(SUM(CASE WHEN status = 'Rahul' THEN value END),0) Rahul
, COALESCE(SUM(CASE WHEN status = 'Vijay' THEN value END),0) Vijay
, COALESCE(SUM(CASE WHEN status = 'Loki' THEN value END),0) Loki
FROM my_table
GROUP
BY MONTH(date);
WITH w AS (
SELECT 10 AS value, 'Rahul' AS status, TO_DATE('20/01/2013', 'DD/MM/YYYY') AS date_time FROM dual
UNION ALL
SELECT 15, 'Vijay', TO_DATE('28/02/2013', 'DD/MM/YYYY') FROM dual
UNION ALL
SELECT 20, 'Loki', TO_DATE('03/02/2013', 'DD/MM/YYYY') FROM dual
UNION ALL
SELECT 25, 'Kiran', TO_DATE('05/01/2013', 'DD/MM/YYYY') FROM dual
UNION ALL
SELECT 5, 'Rahul', TO_DATE('02/01/2013', 'DD/MM/YYYY') FROM dual
UNION ALL
SELECT 15, 'Vijay', TO_DATE('10/01/2013', 'DD/MM/YYYY') FROM dual
UNION ALL
SELECT 08, 'Loki', TO_DATE('01/01/2013', 'DD/MM/YYYY') FROM dual
)
SELECT TO_CHAR(date_time, 'Mon') AS m
, SUM(CASE status WHEN 'Rahul' THEN value ELSE 0 END) AS Rahul
, SUM(CASE status WHEN 'Vijay' THEN value ELSE 0 END) AS Vijay
, SUM(CASE status WHEN 'Loki' THEN value ELSE 0 END) AS Loki
, SUM(CASE status WHEN 'Kiran' THEN value ELSE 0 END) AS Kiran
, SUM(value) AS Total
FROM w
GROUP BY TO_CHAR(date_time, 'Mon')
ORDER BY TO_DATE(TO_CHAR(date_time, 'Mon'), 'Mon')
;