Oracle/SQL Query issue - oracle

I am sort of a newbie to oracle/sql. I am trying to pull from the same column different values and add them with some other information. The other information is not the issue it is trying to count and add here the problem comes in.
I am connecting to an oracle database. Here is what i have
SELECT
EV.PUBLIC_DESCRIPTION,
EV.EVENT_DATE,
ES.PRICE,
BT.BUYER_TYPE_CODE,
PCA.ADDR1,
PCA.ADDR2,
PCA.CITY,
PCA.POSTAL_CODE,
PCE.EMAIL,
PC.FORMATTED_NAME,
PCP.PHONE_NUMBER,
PCP.SECONDARY,
SUM(COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRADLT' THEN 1 ELSE 0 END) + COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRADTE' THEN 1 ELSE 0 END) + COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRSTND' THEN 1 ELSE 0 END) + COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GSTDTE' THEN 1 ELSE 0 END) + COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GROUDI' THEN 1 ELSE 0 END)) AS "Adults",
SUM(COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRCHILD' THEN 1 ELSE 0 END) + COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRCHTE' THEN 1 ELSE 0 END)) AS 'Paid Child',
SUM(COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRPCH' THEN 1 ELSE 0 END)) AS 'Free Child',
SUM(COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRCOMP' THEN 1 ELSE 0 END)) AS 'Comps'
FROM EVENT EV
INNER JOIN EVENT_SEAT ES ON EV.EVENT_ID = ES.EVENT_ID
INNER JOIN BUYER_TYPE BT ON ES.BUYER_TYPE_ID = BT.BUYER_TYPE_ID
INNER JOIN PATRON_ORDER PO ON ES.ORDER_ID = PO.ORDER_ID
INNER JOIN PATRON_ACCOUNT PA ON ES.ATTENDING_PATRON_ACCOUNT_ID = PA.PATRON_ACCOUNT_ID
INNER JOIN PATRON_CONTACT PC ON PA.PATRON_ACCOUNT_ID = PC.PATRON_ACCOUNT_ID
INNER JOIN PATRON_CONTACT_ADDRESS PCA ON PC.PATRON_ACCOUNT_ID = PCA.PATRON_ACCOUNT_ID
INNER JOIN PATRON_CONTACT_EMAIL PCE ON PCA.PATRON_ACCOUNT_ID = PCE.PATRON_ACCOUNT_ID
INNER JOIN PATRON_CONTACT_PHONE PCP ON PCE.PATRON_ACCOUNT_ID = PCP.PATRON_ACCOUNT_ID
GROUP BY EV.PUBLIC_DESCRIPTION, EV.EVENT_DATE
ORDER BY ES.TRANSACTION_ID DESC, PCP.SECONDARY DESC, PCP.PHONE_NUMBER DESC, PC.FORMATTED_NAME DESC, PCE.EMAIL DESC, PCA.POSTAL_CODE DESC, PCA.CITY DESC, PCA.ADDR2 DESC, PCA.ADDR1 DESC, BT.BUYER_TYPE_CODE DESC, ES.PRICE DESC;
any help would be greatly appreciated

You need to decide which technique you want to use, currently you are using 2 techniques and they are colliding.
For this you must know: COUNT() will increment by one for every NON-NULL value
So, to use COUNT() with a case expression do this
COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRSTND' THEN 1 END)
or
COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRSTND' THEN 1 ELSE NULL END)
OR, don't use COUNT(), use SUM() instead
SUM(CASE WHEN BT.BUYER_TYPE_CODE = 'GRSTND' THEN 1 ELSE 0 END)
To add conditions together, I suggest you use the case expression better
Instead of something like this:
, COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRADLT' THEN 1 END)
+ COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRADTE' THEN 1 END)
+ COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRSTND' THEN 1 END)
+ COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GSTDTE' THEN 1 END)
+ COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GROUDI' THEN 1 END) AS "Adults"
Use this:
COUNT(CASE WHEN BT.BUYER_TYPE_CODE IN ('GRADLT','GRADTE','GRSTND','GSTDTE','GROUDI') THEN 1 ELSE NULL END)
There is also an issue with your GROUP BY, which MUST contain ALL non-aggregating columns. I think your query should look more like this:
SELECT
EV.PUBLIC_DESCRIPTION
, EV.EVENT_DATE
, ES.PRICE
/* , BT.BUYER_TYPE_CODE */
, PCA.ADDR1
, PCA.ADDR2
, PCA.CITY
, PCA.POSTAL_CODE
, PCE.EMAIL
, PC.FORMATTED_NAME
, PCP.PHONE_NUMBER
, PCP.SECONDARY
, COUNT(CASE WHEN BT.BUYER_TYPE_CODE IN ('GRADLT', 'GRADTE', 'GRSTND', 'GSTDTE', 'GROUDI') THEN 1 ELSE NULL END) AS "Adults"
, COUNT(CASE WHEN BT.BUYER_TYPE_CODE IN ('GRCHILD', 'GRCHTE', 'GRPCH', 'GRCOMP') THEN 1 ELSE NULL END) AS "Free Child"
, COUNT(CASE WHEN BT.BUYER_TYPE_CODE = 'GRCOMP' THEN 1 ELSE NULL END) AS "Comps"
FROM EVENT EV
INNER JOIN EVENT_SEAT ES
ON EV.EVENT_ID = ES.EVENT_ID
INNER JOIN BUYER_TYPE BT
ON ES.BUYER_TYPE_ID = BT.BUYER_TYPE_ID
INNER JOIN PATRON_ORDER PO
ON ES.ORDER_ID = PO.ORDER_ID
INNER JOIN PATRON_ACCOUNT PA
ON ES.ATTENDING_PATRON_ACCOUNT_ID = PA.PATRON_ACCOUNT_ID
INNER JOIN PATRON_CONTACT PC
ON PA.PATRON_ACCOUNT_ID = PC.PATRON_ACCOUNT_ID
INNER JOIN PATRON_CONTACT_ADDRESS PCA
ON PC.PATRON_ACCOUNT_ID = PCA.PATRON_ACCOUNT_ID
INNER JOIN PATRON_CONTACT_EMAIL PCE
ON PCA.PATRON_ACCOUNT_ID = PCE.PATRON_ACCOUNT_ID
INNER JOIN PATRON_CONTACT_PHONE PCP
ON PCE.PATRON_ACCOUNT_ID = PCP.PATRON_ACCOUNT_ID
GROUP BY
EV.PUBLIC_DESCRIPTION
, EV.EVENT_DATE
, ES.PRICE
/* , BT.BUYER_TYPE_CODE */
, PCA.ADDR1
, PCA.ADDR2
, PCA.CITY
, PCA.POSTAL_CODE
, PCE.EMAIL
, PC.FORMATTED_NAME
, PCP.PHONE_NUMBER
, PCP.SECONDARY
/* check all these columns exist in the select clause
ORDER BY
ES.TRANSACTION_ID DESC
, PCP.SECONDARY DESC
, PCP.PHONE_NUMBER DESC
, PC.FORMATTED_NAME DESC
, PCE.EMAIL DESC
, PCA.POSTAL_CODE DESC
, PCA.CITY DESC
, PCA.ADDR2 DESC
, PCA.ADDR1 DESC
, BT.BUYER_TYPE_CODE DESC
, ES.PRICE DESC
*/
When you come the the final clause: ORDER BY you can ONLY reference columns that exist in the select clause. This example would FAIL
select column1 from table1 group by column1 order by fred
but this would work:
select column1 from table1 group by column1 order by column1

Your column aliases 'Paid Child', 'Free Child', 'Comps' should not be wrapped in single quotes. You should be using double quotes like you are already for "Adults".
So they should instead be:
"Paid Child"
"Free Child"
"Comps"
Or better yet, consider naming your aliases without any spaces, so you don't have to worry about wrapping the aliases in anything, like this:
paid_child
free_child
comps
Documentation on Database Object Names and Qualifiers:
Database Object Naming Rules
Every database object has a name. In a SQL statement, you represent the name of an object with a quoted identifier or a nonquoted identifier.
A quoted identifier begins and ends with double quotation marks ("). If you name a schema object using a quoted identifier, then you must use the double quotation marks whenever you refer to that object.
A nonquoted identifier is not surrounded by any punctuation.
...
Although column aliases, table aliases, usernames, and passwords are not objects or parts of objects, they must also follow these naming rules unless otherwise specified in the rules themselves.

Related

Count and Sum inside a select with multiple sums and counts

I'm using sub-query factoring and I have a query that returns invoice lines, and in the end I have this final sub-query:
I've already tried Partition but without success
SELECT
COUNT(CASE WHEN PC <> 0 THEN 1 END) AS A_LINECOUNT,
SUM(CASE WHEN PC > 0 THEN NR ELSE 0 END) AS B_PRODUCTCOUNT,
COUNT(CASE WHEN ALLOW_PAY = 1 THEN 1 END) AS C_INVOICECOUNT, --- ERROR
SUM(CASE WHEN ALLOW_PAY = 1 THEN MISSING_VALUE ELSE 0 END) AS D_INVOICETOTAL, --- ERROR
COUNT(CASE WHEN IS_NON_LIQUIDABLE_PRODUCT = 1 THEN 1 END) AS E_CONDITIONCOUNT,
COUNT(CASE WHEN IS_LIQUIDABLE_PRODUCT = 1 THEN 1 END) AS F_CONDITIONCOUNT
FROM MAIN_Q
The calculation of C_INVOICECOUNT and D_INVOICETOTAL is not correct because their values are repeated within each line of the invoice. Please consider that um MAIN_Q i also have a document_id where i can group by.
thanks
Maybe I understood correctly, maybe not, but this is too long for comment. If yes, C_INVOICECOUNT can be count as:
count(distinct case when allow_pay = 1 then document_id end)
But the problem is with D_INVOICETOTAL. You have repeated values for each invoice here and details which do not repeat. If so, add row numbering to your query:
select main_q.*, row_number() over (partition by document_id) rn from main_q
and then in problematic places use rn = 1:
select ...
count(case when rn = 1 and allow_pay = 1 then 1 end),
sum(case when rn = 1 and allow_pay = 1 then missing_value else 0 end)
...
from (select main_q.*, row_number() over (partition by document_id) rn from main_q)
Only first rows for each invoice will be analysed. Of course you can add row_number in earlier step.

Adding filters in subquery from CTE quadruples run time

I am working on an existing query for SSRS report that focuses on aggregated financial aid data split out into 10 aggregations. User wants to be able to select students included in that aggregated data based on new vs. returning and 'selected for verification.' For the new/returning status, I added a CTE to return the earliest admit date for a student. 2 of the 10 data fields are created by a subquery. I have been trying for 3 days to get the subquery to use the CTE fields for a filter, but they won't work. Either they're ignored or I get a 'not a group by expression' error. If I put the join to the CTE within the subquery, the query time jumps from 45 second to 400 seconds. This shouldn't be that complicated! What am I missing? I have added some of the code... 3 of the chunks work - paid_something doesn't.
with stuStatus as
(select
person_uid, min(year_admitted) admit_year
from academic_study
where aid_year between :AidYearStartParameter and :AidYearEndParameter
group by person_uid)
--- above code added to get student information not originally in qry
select
finaid_applicant_status.aid_year
, count(1) as fafsa_cnt --works
, sum( --works
case
when (
package_complete_date is not null
and admit.status is not null
)
then 1
else 0
end
) as admit_and_package
, (select count(*) --does't work
from (
select distinct award_by_aid_year.person_uid
from
award_by_aid_year
where
award_by_aid_year.aid_year = finaid_applicant_status.aid_year
and award_by_aid_year.total_paid_amount > 0 )dta
where
(
(:StudentStatusParameter = 'N' and stuStatus.admit_year = finaid_applicant_status.aid_year)
OR
(:StudentStatusParameter = 'R' and stuStatus.admit_year <> finaid_applicant_status.aid_year)
OR :StudentStatusParameter = '%'
)
)
as paid_something
, sum( --works
case
when exists (
select
1
from
award_by_person abp
where
abp.person_uid = fafsa.person_uid
and abp.aid_year = fafsa.aid_year
and abp.award_paid_amount > 0
) and fafsa.requirement is not null
then 1
else 0
end
) as paid_something_fafsa
from
finaid_applicant_status
join finaid_tracking_requirement fafsa
on finaid_applicant_status.person_uid = fafsa.person_uid
and finaid_applicant_status.aid_year = fafsa.aid_year
and fafsa.requirement = 'FAFSA'
left join finaid_tracking_requirement admit
on finaid_applicant_status.person_uid = admit.person_uid
and finaid_applicant_status.aid_year = admit.aid_year
and admit.requirement = 'ADMIT'
and admit.status in ('M', 'P')
left outer join stuStatus
on finaid_applicant_status.person_uid = stuStatus.person_uid
where
finaid_applicant_status.aid_year between :AidYearStartParameter and :AidYearEndParameter
and (
(:VerifiedParameter = '%') OR
(:VerifiedParameter <> '%' AND finaid_applicant_status.verification_required_ind = :VerifiedParameter)
)
and
(
(:StudentStatusParameter = 'N' and (stuStatus.admit_year IS NULL OR stuStatus.admit_year = finaid_applicant_status.aid_year ))
OR
(:StudentStatusParameter = 'R' and stuStatus.admit_year <> finaid_applicant_status.aid_year)
OR :StudentStatusParameter = '%'
)
group by
finaid_applicant_status.aid_year
order by
finaid_applicant_status.aid_year
Not sure if this helps, but you have something like this:
select aid_year, count(1) c1,
(select count(1)
from (select distinct person_uid
from award_by_aid_year a
where a.aid_year = fas.aid_year))
from finaid_applicant_status fas
group by aid_year;
This query throws ORA-00904 FAS.AID_YEAR invalid identifier. It is because fas.aid_year is nested too deep in subquery.
If you are able to modify your subquery from select count(1) from (select distinct sth from ... where year = fas.year) to select count(distinct sth) from ... where year = fas.year then it has the chance to work.
select aid_year, count(1) c1,
(select count(distinct person_uid)
from award_by_aid_year a
where a.aid_year = fas.aid_year) c2
from finaid_applicant_status fas
group by aid_year
Here is simplified demo showing non-working and working queries. Of course your query is much more complicated, but this is something what you could check.
Also maybe you can use dbfiddle or sqlfiddle to set up some test case? Or show us sample (anonimized) data and required output for them?

procedure failurecompilation

I have an existing procedure which creates a table adwstg.switchhold_notificatn_stg
Suddenly it is throwing error in creating the table. I didn't change anything the statement.
First I thought the error is with ''No'' . So find & replace '' with '
But it is throwing error at line:
nvl(ba300_z51.sent_650_01, 'No') sent_650_01,
error(27,29): PLS-00103: Encountered the symbol "NO" when expecting one of the following: * & = - + ; < / > at in is mod remainder not rem <> or != or ~= >= <= <> and or like like2 like4 likec between || multiset member submultiset***
Below is the query :
create table adwstg.switchhold_notificatn_stg nologging parallel (degree 8) compress as
select distinct
bad3700.createdon,
bad3700.uc_pod_ext,
bpc.cacont_acc,
bad3700.notificatn,
bad3700.nfcat_code,
nvl(ba300_z51.sent_650_01, ''No'') sent_650_01,
decode(ba300_z51.sent_650_01,''No'',''--'',''Yes'',to_char(ba300_z51.ucswmsgdat,''yyyymmdd''),''--'') date_sent_650_01,
nvl(to_char(ba300_z51.ucswmsgtim,''hh24:mi:ss''),''--'') time_sent_650_01,
nvl(ba300_z52.received_650_02, ''No'') received_650_02,
decode(ba300_z52.received_650_02,''No'',''--'',''Yes'',to_char(ba300_z52.ucswmsgdat,''yyyymmdd''),''--'') date_received_650_02,
nvl(to_char(ba300_z52.ucswmsgtim,''hh24:mi:ss''),''--'') time_received_650_02,
nvl(ba300_z20.received_814_20, ''No'') received_814_20,
decode(ba300_z20.received_814_20,''No'',''--'',''Yes'',to_char(ba300_z20.ucswmsgdat,''yyyymmdd''),''--'') date_received_814_20,
nvl(to_char(ba300_z20.ucswmsgtim,''hh24:mi:ss''),''--'') time_received_814_20,
case
when trim(bad3700.nfcat_code) = ''SH01'' and zet.ext_ui is not null then ''ADDED''
when trim(bad3700.nfcat_code) = ''SH01'' and zet.ext_ui is null then ''NOT PROCESSED''
when trim(bad3700.nfcat_code) in (''SH02'',''SH03'') and zet.ext_ui is null then ''REMOVED''
when trim(bad3700.nfcat_code) in (''SH02'',''SH03'') and zet.ext_ui is not null then ''NOT PROCESSED''
else ''NOT PROCESSED''
end work_order_check
from
(select distinct *
from
(select
trunc(createdon) createdon,
trim(notificatn) notificatn,
trim(uc_pod_ext) uc_pod_ext,
trim(not_type) not_type,
trim(nfcat_code) nfcat_code,
row_number () over (partition by trim(uc_pod_ext),trunc(createdon) order by trim(notificatn) desc) rnum
from birpt.bic_azfc_ds3700
where upper(trim(not_type)) = ''SH''
and trim(bic_zdiscstat) = ''E0010'')
where rnum = 1
) bad3700
left outer join
(
select distinct ucinstalla, uc_pod_ext, datefrom, dateto
from birpt.bi0_qucinstalla
where objvers = ''A''
) bqi
on (trim(bad3700.uc_pod_ext) = trim(bqi.uc_pod_ext)
and trunc(bad3700.createdon) between bqi.datefrom and bqi.dateto)
left outer join
(
select distinct cacont_acc, ucinstalla, ucmovein_d, ucmoveoutd
from birpt.bi0_puccontract
where objvers = ''A''
) bpc
on (trim(bqi.ucinstalla) = trim(bpc.ucinstalla)
and trunc(bad3700.createdon) between bpc.ucmovein_d and bpc.ucmoveoutd)
left outer join
(select distinct *
from
(select
trim(ucswtpodex) ucswtpodex,
trunc(ucswmsgdat) ucswmsgdat,
ucswmsgtim,
case --650_01 CHECK
when trim(uc_mdcat) = ''Z51'' then ''Yes''
else ''No''
end sent_650_01,
row_number () over (partition by trim(ucswtpodex), trunc(ucswmsgdat) order by trunc(ucswmsgdat) desc, ucswmsgtim desc) rnum
from birpt.bic_azudeds0300
where trim(uc_mdcat) = ''Z51'')
where rnum = 1) ba300_z51
on (trim(bad3700.uc_pod_ext) = trim(ba300_z51.ucswtpodex)
and trunc(bad3700.createdon)= trunc(ba300_z51.ucswmsgdat))
left outer join
(select distinct *
from
(select
trim(ucswtpodex) ucswtpodex,
trunc(ucswmsgdat) ucswmsgdat,
ucswmsgtim,
case --650_02 CHECK
when trim(uc_mdcat) = ''Z52'' then ''Yes''
else ''No''
end received_650_02,
row_number () over (partition by trim(ucswtpodex), trunc(ucswmsgdat) order by trunc(ucswmsgdat) desc, ucswmsgtim desc) rnum
from birpt.bic_azudeds0300
where trim(uc_mdcat) = ''Z52'')
where rnum = 1) ba300_z52
on (trim(bad3700.uc_pod_ext) = trim(ba300_z52.ucswtpodex)
and trunc(bad3700.createdon)= trunc(ba300_z52.ucswmsgdat))
left outer join
(select distinct *
from
(select
trim(ucswtpodex) ucswtpodex,
trunc(ucswmsgdat) ucswmsgdat,
ucswmsgtim,
case --814_20 CHECK
when trim(uc_mdcat) = ''Z20'' then ''Yes''
else ''No''
end received_814_20,
row_number () over (partition by trim(ucswtpodex), trunc(ucswmsgdat) order by trunc(ucswmsgdat) desc, ucswmsgtim desc) rnum
from birpt.bic_azudeds0300
where trim(uc_mdcat) = ''Z20'')
where rnum = 1) ba300_z20
on (trim(bad3700.uc_pod_ext) = trim(ba300_z20.ucswtpodex)
and trunc(bad3700.createdon)= trunc(ba300_z20.ucswmsgdat))
left outer join
(select distinct ext_ui
from isurpt.zcs_esiid_tamper
) zet
on (trim(bad3700.uc_pod_ext) = trim(zet.ext_ui));
If you remove all doubled single quotes (perform replace function in any text editor), your code will be valid (as far as syntax is concerned).
I don't have your tables to test it, and there are too many of them with too many columns to create a test case by myself.
The question is: why did you double them in the first place?

Oracle Pivot options

I have the below Pivot and output. I would like to display the below.
Remove the parentheses around the columns?
Add indicator of X and Null in substitute of 1 and 0?
SQL:
SELECT DISTINCT
*
FROM (
SELECT D.ID, D.DI, A.ID
FROM A
LEFT JOIN AD ON A.ID = AD.ID
LEFT JOIN D ON AD.ID = D.ID
WHERE 1=1
AND A.ID = 890929
)
PIVOT
(
COUNT(ID)
FOR DI IN ( 'Low med','Soft','Regular','High Med','Other')
)
Query output:
ID 'Low med' 'Soft' 'Regular' 'High Med' 'Other'
1 1 1 0 0 1
Expected output:
ID LOW_MED SOFT REGULAR HIGH_MED OTHER
1 X X NULL NULL X
You can remove the single quotes (not parentheses, which are ()), by aliasing the pivoted expressions:
FOR DI IN ('Low med' as low_med, 'Soft' as soft, 'Regular' as regular,
'High Med' as high_med,'Other' as other)
You can then use those aliases for the second part, but adding case expressions to your main query:
SELECT id,
case when low_med = 1 then 'X' else null end as low_med,
case when soft = 1 then 'X' else null end as soft,
case when regular = 1 then 'X' else null end as regular,
case when high_med = 1 then 'X' else null end as high_med,
case when other = 1 then 'X' else null end as other
FROM (
SELECT D.ID, D.DI, A.ID
FROM A
LEFT JOIN AD ON A.ID = AD.ID
LEFT JOIN D ON AD.ID = D.ID
WHERE 1=1
AND A.ID = 890929
)
PIVOT
(
COUNT(ID)
FOR DI IN ('Low med' as low_med, 'Soft' as soft, 'Regular' as regular,
'High Med' as high_med,'Other' as other)
)

Count Performance optimisation

I got 2 versions of basically the same code. (See below) Version 1 is running at 2 seconds, version 2 is running at .5 - .6 seconds. There are 10 million rows currently from where I am selecting from, but this number goes up pretty fast. I would like to go even lower if possible. The problem is that I use Version 2, and I need to call that 30 times (different statuses, different usernames, etc), the final number is still going to be too big for what I need. Is there a 3rd version I could use instead? Or is there any other way I could make this to be even faster? Or the only thing that I could do is play with indexes.
Basically all these counts would be displayed in the most visited screen in a web application, and 30 * .5 seconds sounds a bit too much when 1000 users are using the system in the same time.
Version 1
declare #a1 datetime; set #a1 = GETDATE()
declare #int1 INT,#int2 INT,#int3 INT,#int4 INT,#int5 INT,#int6 INT,#int7 INT,#int8 INT
select #int1 = COUNT(Id) from ToDos where StatusId = 1 and stringUserId = 'a'
select #int2 = COUNT(Id) from ToDos where StatusId = 1 and stringUserId = 'b'
select #int3 = COUNT(Id) from ToDos where StatusId = 1 and stringUserId = 'c'
select #int4 = COUNT(Id) from ToDos where StatusId = 1 and stringUserId = 'd'
select #int5 = COUNT(Id) from ToDos where StatusId = 1 and stringUserId = 'e'
select #int6 = COUNT(Id) from ToDos where StatusId = 1 and stringUserId = 'f'
select #int7 = COUNT(Id) from ToDos where StatusId = 1 and stringUserId = 'g'
select #int8 = COUNT(Id) from ToDos where StatusId = 1 and stringUserId = 'h'
select #int1, #int2, #int3, #int4, #int5, #int6, #int7, #int8
SELECT DATEDIFF(MILLISECOND, #a1, GETDATE())
Version 2
declare #a1 datetime; set #a1 = GETDATE()
select stringUserId, count(stringUserId)
from ToDos
where StatusId = 1 and stringUserId in ('a','b','c','d','e','f','g','h')
group by stringUserId
order by COUNT(stringUserId) desc
SELECT DATEDIFF(MILLISECOND, #a1, GETDATE())
Try conditional count.
select
#int1 = COUNT(CASE WHEN stringUserId = 'a' THEN 1 END),
#int2 = COUNT(CASE WHEN stringUserId = 'b' THEN 1 END),
#int3 = COUNT(CASE WHEN stringUserId = 'c' THEN 1 END),
#int4 = COUNT(CASE WHEN stringUserId = 'd' THEN 1 END),
#int5 = COUNT(CASE WHEN stringUserId = 'e' THEN 1 END),
#int6 = COUNT(CASE WHEN stringUserId = 'f' THEN 1 END),
#int7 = COUNT(CASE WHEN stringUserId = 'g' THEN 1 END),
#int8 = COUNT(CASE WHEN stringUserId = 'h' THEN 1 END)
from ToDos
where StatusId = 1
FYI: I didnt include the ELSE part for CASE because for default will return NULL and COUNT doesnt count nulls
You could try:
select a.* from (select stringUserId, count(stringUserId) as IDCount
from ToDos
where StatusId = 1 and stringUserId in ('a','b','c','d','e','f','g','h')
group by stringUserId) a
order by a.IDCount desc
that eliminates the count function from the order by

Resources