Select one column (with multiple rows) 5 times from the same table with different dates in the where clause - pivot

The DB records all user activity daily. I am trying to compile a summary report to display total number of actions per day per user. The problem is I want to stack the results next to each other. I have refered to the following stackoverflow questions.
mysql Select one column twice from the same table with different dates in the where clause
Select two columns from same table with different WHERE conditions
but I still continue to get the "subquery returns more than one row error #1242". All help is appreciated. Thank you.
This is my query, just for 2 days to start with.
SELECT LOGGEDIN_USER AS EnquiryHero,
( SELECT COUNT(user_id) from applications
DATE_TIME like "2016-08-24%" group by user_id ) as Day1,
( SELECT COUNT(user_id)from applications
WHERE DATE_TIME like "2016-08-25%" group by user_id ) as Day2,
from applications WHERE DATE_TIME like "2016-08-24%" group by user_id;
--
SELECT user_id,
( SUM( IF( the_day ='2016-08-24', ct, 0 ))) AS 2016-08-24,
( SUM( IF( the_day ='2016-08-25', ct, 0 ))) AS 2016-08-25,
( SUM( IF( the_day ='2016-08-26', ct, 0 ))) AS 2016-08-26,
( SUM( IF( the_day ='2016-08-27', ct, 0 ))) AS 2016-08-27,
FROM ( select user_id, DATE(date_time) AS the_day, loggedin_user, COUNT(*) AS ct
FROM applications GROUP BY 1,2 ) AS x
GROUP BY user_id;

First focus on getting the data; then focus on "pivoting" the data.
SELECT user_id,
DATE(`date_time`) AS the_day,
COUNT(*) AS ct
FROM applications
GROUP BY 1, 2;
See if that gives you the data desired; then look at how to "pivot". See the extra tag I added.
Then pivot
SELECT user_id,
(SUM(IF(the_day = '2016-08-24', ct, 0) AS '2016-08-24',
(SUM(IF(the_day = '2016-08-25', ct, 0) AS '2016-08-25',
(SUM(IF(the_day = '2016-08-26', ct, 0) AS '2016-08-26',
(SUM(IF(the_day = '2016-08-27', ct, 0) AS '2016-08-27',
...
FROM (
the query above
) AS x
GROUP BY user_id;

Related

Is there anyway to create a pivot table with all these calculated fields?

I have a table of Name, date (every day of the year), and hours. I am trying to create a pivot table to analyze the compliance of the data. By that I mean, I need to know for every year how many people are complainant with the 1800 limit (sum of all hours for the year) and how many are not.
i created the required results via 4 tables see image but because i am using so many table, i am unable to do any drilldown/drill up analyzes. Is there a way to combine all of this in one table?
Add your Pivot Table to the Data Model and then create three new measures:
CompliantCheck :=
IF (
ISFILTERED ( Table1[Name] ),
IF ( SUM ( Table1[Hours] ) > 1800, "Non-Compliant", "Compliant" ),
""
)
CompliantCount :=
IF (
[CompliantCheck] = "",
"",
0
+ CALCULATE (
DISTINCTCOUNT ( [Name] ),
FILTER ( ALL ( Table1[Name] ), [CompliantCheck] = "Compliant" )
)
)
NonCompliantCount :=
IF (
[CompliantCheck] = "",
"",
0
+ CALCULATE (
DISTINCTCOUNT ( [Name] ),
FILTER ( ALL ( Table1[Name] ), [CompliantCheck] = "Non-Compliant" )
)
)
Obviously change the names of the table and fields in the above if necessary. Your Pivot Table should then comprise:
Rows: Name and Fiscal Year
Values: Sum of Hours, Compliant Check, CompliantCount, NonCompliantCount

force 0 when blank with addcolumn summarize excel 2016 dax for more accurate averages

I have one table that has three columns: lisa, customers and activity_type. I want to count the number of rows by customer and activity type and then average them over all customers by activity types.
If this were a table in sql, I'd do
SELECT
lisa,
customer,
activity_type,
average(ct)
FROM
(
SELECT
lisa,
customer,
activity_type,
CASE
WHEN
s.ct IS NULL
THEN
0
ELSE
s.ct
END
ct
FROM
(
SELECT
*
FROM
(
SELECT DISTINCT
lisa,
customer
FROM
TABLE
)
,
(
SELECT DISTINCT
activity_type
)
)
LEFT JOIN
(
SELECT
lisa,
customer,
activity_type,
COUNT(*) ct
FROM
TABLE
GROUP BY
1,
2,
3
)
s
)
s
But it's Dax, which is infinitely harder. I tried:
=
AVERAGEX(
ADDCOLUMNS(
CROSSJOIN( VALUES( Query1[customer] ), VALUES( Query1[activity_type] ) ),
"C", CALCULATE( COUNTA( Query1[engagio_activity_id] ) + 0 )
),
IF( [C] = BLANK(), 0, [C] )
)
and
=
AVERAGEX(
ADDCOLUMNS(
SUMMARIZE( Query1[lisa], Query1[activity_type] ),
"C", CALCULATE( COUNTA( Query1[engagio_activity_id] ) + 0 )
),
IF( [C] = BLANK(), 0, [C] )
)
But try as I might, I still get:
Where the blanks are not treated as 0 in the aggregate rows such as the "no" row in the picture above. That roll up amount ignores the blanks when calculating the averages. When I put the cross join into the dax studio, I forced the 0's
So it's a mystery to me where the 0s went.
I think you are complicating
Average=
VAR totalCustomers = COUNTROWS(ALL(Query1[customer])) //this gives you total # of customers
RETURN
DIVIDE(COUNT(Query1[engagio_activity_id]) + 0, //the +0 forces the count to always return something
totalCostumers)

DAX sum of multiplication (sumproduct) across multiple tables

I am struggling with what I think is a really silly problem.
I am trying to get "MTD target" values from an arbitrary date selection. I have a table 'out' which has many dimensions +date, as well as a target table which gives me a constant target value per day, for each month. My goal is to get the number of days selected per EACH month and multiply it by the corresponding daily target for the relevant month.
For example, month 1 daily target is 2, month 2 daily target is 4. I have 4 days in month 1, and 3 days in month 2. My cumulative target should be 2*4+3*2 = 14.
I can do this for a single month no problem. But as soon as I have a date range selected that crosses 2 or more months it all goes to hell.
Table 'out' has date, country, and other dimensions.
Table 'targets' has a year, month, and country dimensions.
I am trying to get some join and multiplication that is something like SUM(month_country * selected_days)
Here are the DAX measures I've tried:
mtd_inv_tgt :=
CALCULATE (
SUM ( targets[daily_spend] ),
FILTER (
targets,
targets[market] = FIRSTNONBLANK ( out[co_market], "" )
&& targets[yyyymm] >= MIN ( out[yyyymm] )
&& targets[yyyymm] <= MAX ( out[yyyymm] )
)
)
* DISTINCTCOUNT ( out[date] )
mtd_inv_tgt :=
SUMX (
FILTER (
targets,
targets[market] = FIRSTNONBLANK ( out[co_market], "" )
&& targets[yyyymm] >= MIN ( out[yyyymm] )
&& targets[yyyymm] <= MAX ( out[yyyymm] )
),
targets[daily_spend] * DISTINCTCOUNT ( out[date] )
)
This works fine if the dates selected belong to one month. If I select 2 months it will add the daily spend across 2 months and then multiply it by the number of dates covering the 2 months. Like from the above example it would be (2+3)*(4+2) = 30, which is obviously wrong.
The caveat is I can't use SUMX on the 'out' table because there are many records per date+country, whilst the targets are a single entry per month+country.
I think something similar to this should work:
mtd_inv_tgt :=
SUMX (
VALUES ( out[date] ),
LOOKUPVALUE (
targets[daily_spend],
targets[yyyymm], SELECTEDVALUE ( out[yyymm] )
)
)
This iterates over each distinct out[date] value in the current filter context and adds up the daily_spend for each of those dates that it looks up by matching on yyymm.
Iterating over only the yyymm might be more efficient:
mtd_inv_tgt :=
SUMX (
VALUES ( out[yyymm] ),
DISTINCTCOUNT ( out[date] )
* LOOKUPVALUE (
targets[daily_spend],
targets[yyyymm], EARLIER ( out[yyymm] )
)
)
Note: If these don't work as expected, please provide sample data to check against as I haven't actually tested these.

Power BI: Combining cells from a column where given a condition

I have to perform a task in power BI (DAX) where i have a list of users and their fields of work.
I have to combine all the fields corresponding to every user and find the highest frequency combination.
Below is how I was planning to do it.
How can i generate the "Expected Result" from the "Sample" file?
Sample:
ID Value
a medicine
b automobile
c banking
d scientist
a banking
a scientist
d banking
Expected Result:
ID Value Combi
a medicine|banking|scientist
b automobile
c banking
d scientist|banking
You can concatenate values from multiple rows and generate a delimited string by using CONCATENATEX() DAX function. Then use ADDCOLUMNS and SUMMARIZE to get the desired result.
Expected Table =
SUMMARIZE (
ADDCOLUMNS (
'Table',
"Combined Value", CONCATENATEX (
FILTER (
SUMMARIZE ( 'Table', 'Table'[ID], [Value] ),
[ID] = EARLIER ( 'Table'[ID] )
),
'Table'[Value],
"|"
)
),
[ID],
[Combined Value]
)
It produces:
Break down the logic
The easiest way in my opinion is create a calculated column in your table to generate the combined value column:
Combined Value =
CONCATENATEX (
FILTER (
SUMMARIZE ( 'Table', 'Table'[ID], [Value] ),
[ID] = EARLIER ( 'Table'[ID] )
),
'Table'[Value],
"|"
)
Then you can create a summarized table based on your table with the previously created calculated column. To create a calculated table go to the Modeling tab and click the New Table icon.
Use this expression:
Resumed Table =
SUMMARIZE ( 'Table', [ID], 'Table'[Combined Value] )
You will get a table like this:
While both methods work just fine, the recommend way to approach this issue is directly from Power Query or from your source.
Let me know if this helps.

Nested Sum( ) query is not working in mysql

i'm having a problem in calculating total bill of a ptient. I have three tables named as "test", "pharmacy", "check".
Columns in test are:
patient_ID
testname
rate
Columns in pharmacy are:
patient_ID
medicineDescription
qty
rate
Columns in check are:
patient_ID
doctorID
fees
date
I have a table Bill that will store total amount of a patient.
patient_ID
amount
date
I have used the following query. But it's giving the following error.
$result = mysqli_query($data, "SELECT patient_ID, (SUM(pharmacy.qty*pharmacy.rate ) + SUM(test.rate) + SUM(check.fees))
AS total FROM pharmacy, test, check WHERE patient_ID= '$pID'" );
Correct query should be, closing bracket was missing at the end of subquery (... AS total FROM pharmacy**)**):
$result = mysqli_query ($data, "SELECT patient_ID,
(SUM(pharmacy.qty*pharmacy.rate ) + SUM(test.rate) + SUM(check.fees)) AS total FROM pharmacy),
test,
check
WHERE patient_ID= '$pID'" );
You have three tables in your from clause, but with no join condition - this means you're pairing each row with all the other rows, which is obviously not what you intended. One way to handle this is to use proper joins:
SELECT p.patient_id, pharmacy_sum + test_sum + fees_sum AS total
FROM (SELECT patient_id, SUM(qty * rate) AS pharmacy_sum
FROM pharmacy
WHERE patient_ID= '$pID'
GROUP BY patient_id) p
JOIN (SELECT patient_id, SUM(rate) AS test_sum
FROM test
WHERE patient_ID= '$pID'
GROUP BY patient_id) t ON p.patient_id_id = t.patient_id
JOIN (SELECT patient_id, SUM(fees) AS fees_sum
FROM check
WHERE patient_ID= '$pID'
GROUP BY patient_id) c ON p.patient_id_id = c.patient_id

Resources